diff --git a/.azure-ci.yml b/.azure-ci.yml index c8bc8691826f..2e16a0989fe5 100644 --- a/.azure-ci.yml +++ b/.azure-ci.yml @@ -8,10 +8,20 @@ trigger: include: - master - release/3.0 + paths: + exclude: + - Documentation/* + - /*.md pr: -- master -- release/3.0 + branches: + include: + - master + - release/3.0 + paths: + exclude: + - Documentation/* + - /*.md resources: containers: @@ -36,31 +46,36 @@ resources: jobs: # Windows legs - template: /eng/pipelines/windows.yml - ${{ if and(ne(variables['System.TeamProject'], 'public'), notIn(variables['Build.Reason'], 'PullRequest')) }}: - parameters: - isOfficialBuild: true + parameters: + isOfficialBuild: ${{ and(ne(variables['System.TeamProject'], 'public'), notIn(variables['Build.Reason'], 'PullRequest')) }} + fullMatrix: ${{ notIn(variables['Build.Reason'], 'PullRequest') }} # Linux legs - template: /eng/pipelines/linux.yml - ${{ if and(ne(variables['System.TeamProject'], 'public'), notIn(variables['Build.Reason'], 'PullRequest')) }}: - parameters: - isOfficialBuild: true + parameters: + isOfficialBuild: ${{ and(ne(variables['System.TeamProject'], 'public'), notIn(variables['Build.Reason'], 'PullRequest')) }} + fullMatrix: ${{ notIn(variables['Build.Reason'], 'PullRequest') }} # MacOS legs - template: /eng/pipelines/macos.yml - ${{ if and(ne(variables['System.TeamProject'], 'public'), notIn(variables['Build.Reason'], 'PullRequest')) }}: - parameters: - isOfficialBuild: true + parameters: + isOfficialBuild: ${{ and(ne(variables['System.TeamProject'], 'public'), notIn(variables['Build.Reason'], 'PullRequest')) }} + fullMatrix: ${{ notIn(variables['Build.Reason'], 'PullRequest') }} - # Only run in official builds - - ${{ if and(ne(variables['System.TeamProject'], 'public'), notIn(variables['Build.Reason'], 'PullRequest')) }}: - # Redhat6 leg is only for official builds - - template: /eng/pipelines/redhat6.yml + # RedHat6 leg + - template: /eng/pipelines/redhat6.yml + parameters: + isOfficialBuild: ${{ and(ne(variables['System.TeamProject'], 'public'), notIn(variables['Build.Reason'], 'PullRequest')) }} + fullMatrix: ${{ notIn(variables['Build.Reason'], 'PullRequest') }} # FreeBSD leg is only for official builds # - template: /eng/pipelines/freebsd.yml + # parameters: + # isOfficialBuild: ${{ and(ne(variables['System.TeamProject'], 'public'), notIn(variables['Build.Reason'], 'PullRequest')) }} + # fullMatrix: ${{ notIn(variables['Build.Reason'], 'PullRequest') }} - # Publish step + # Publish step. Only run in official builds + - ${{ if and(ne(variables['System.TeamProject'], 'public'), notIn(variables['Build.Reason'], 'PullRequest')) }}: - template: /eng/pipelines/publish.yml parameters: dependsOn: diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 000000000000..63401b98a8ba --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,18 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "coverlet.console": { + "version": "1.5.1", + "commands": [ + "coverlet" + ] + }, + "dotnet-reportgenerator-globaltool": { + "version": "4.1.6", + "commands": [ + "reportgenerator" + ] + } + } +} \ No newline at end of file diff --git a/.gitattributes b/.gitattributes index 9ae9a523dc8c..b73e97feb3d2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -10,14 +10,14 @@ # default for csharp files. # Note: This is only used by command line ############################################################################### -#*.cs diff=csharp +*.cs diff=csharp ############################################################################### # Set the merge driver for project and solution files # # Merging from the command prompt will add diff markers to the files if there # are conflicts (Merging from VS is not affected by the settings below, in VS -# the diff markers are never inserted). Diff markers may cause the following +# the diff markers are never inserted). Diff markers may cause the following # file extensions to fail to load in VS. An alternative would be to treat # these files as binary and thus will always conflict and require user # intervention with every merge. To do so, just uncomment the entries below @@ -46,9 +46,9 @@ ############################################################################### # diff behavior for common document formats -# +# # Convert binary document formats to text before diffing them. This feature -# is only available from the command line. Turn it on by uncommenting the +# is only available from the command line. Turn it on by uncommenting the # entries below. ############################################################################### #*.doc diff=astextplain diff --git a/Directory.Build.props b/Directory.Build.props index c804e8f4766a..cd0a0b004f12 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -18,7 +18,7 @@ true $(MSBuildThisFileDirectory)artifacts\toolset\Common\ - true + $([System.Text.RegularExpressions.Regex]::IsMatch($(MSBuildProjectDirectory), 'src%24')) @@ -114,25 +114,6 @@ $([MSBuild]::NormalizeDirectory('$(RepoRoot)', 'src')) - - - $(DotNetRestorePackagesPath) - $([MSBuild]::EnsureTrailingSlash('$(NuGetPackageRoot)')) - $(RepoRoot).packages/ - - $(DOTNET_INSTALL_DIR) - $(RepoRoot).dotnet\ - $(DotNetRoot)\ - $(DotNetRoot) - "$(DotNetRoot)dotnet" - $(DotNetRoot)dotnet - $(DotNetCmd).exe - - - - - $(MSBuildToolsPath)\Microsoft.Common.targets @@ -167,7 +148,8 @@ Library Open - true + $(IsSourceProject) + $(IsSourceProject) $(RepositoryEngineeringDir)DefaultGenApiDocIds.txt true @@ -267,7 +249,7 @@ - true + true optimization.windows_nt-x64.IBC.CoreFx $(optimizationwindows_ntx64IBCCoreFxPackageVersion) @@ -315,9 +297,7 @@ strict 4 true - - - false + true false @@ -329,8 +309,8 @@ true true - - $(NoWarn);BCL0020 + + $(NoWarn);CS8609;CS8610 @@ -360,8 +340,6 @@ $(RefRootPath)netstandard/ $(RefRootPath)netstandard2.1/ $(RefRootPath)netfx/ - - $([MSBuild]::NormalizeDirectory('$(RepoRoot)', '.tools', 'globaltools')) $([MSBuild]::NormalizeDirectory('$(ArtifactsDir)', 'ibc')) $([MSBuild]::NormalizeDirectory('$(ArtifactsToolsetDir)', 'ilasm')) $([MSBuild]::NormalizeDirectory('$(ArtifactsToolsetDir)', 'ILLink')) @@ -389,7 +367,6 @@ true - true true true @@ -397,8 +374,6 @@ $([MSBuild]::NormalizeDirectory('$(ArtifactsBinDir)', 'testhost', '$(BuildConfiguration)')) $([MSBuild]::NormalizeDirectory('$(TestHostRootPath)', 'host', 'fxr', '$(NETCoreAppTestSharedFxVersion)')) $([MSBuild]::NormalizeDirectory('$(TestHostRootPath)', 'shared', 'Microsoft.NETCore.App', '$(NETCoreAppTestSharedFxVersion)')) - $(TestHostRootPath)ILCInputFolder - $(TestHostRootPath)TestILC $(TestHostRootPath)UAPLayout @@ -422,27 +397,18 @@ - - - - - - $(DefineConstants),uap $(DefineConstants),uapaot $(DefineConstants),netfx $(DefineConstants),netstandard + $(DefineConstants),NETSTANDARD10 $(DefineConstants),netcoreapp $(DefineConstants),netcoreapp20 - - true - true @@ -456,6 +422,7 @@ true + diff --git a/Directory.Build.targets b/Directory.Build.targets index 8591539bf844..8923127a4df6 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -15,6 +15,7 @@ $(TestStrongNameKeyId) + @@ -82,10 +83,6 @@ $(NETCoreAppTestSharedFrameworkPath) - - - $(ILCFXInputFolder) - $(UAPTestSharedFrameworkPath) @@ -125,30 +122,14 @@ - - - - - - - - - - - - - - - @@ -170,6 +151,7 @@ <_GenAPICmd>$(_GenAPICmd) --out "$(_RefSourceFileOutputPath)" <_GenAPICmd>$(_GenAPICmd) --exclude-attributes-list "$(_ExcludeAPIList)" <_GenAPICmd>$(_GenAPICmd) --header-file "$(_LicenseHeaderTxtPath)" + <_GenAPICmd Condition="'$(LangVersion)' != ''">$(_GenAPICmd) --lang-version "$(LangVersion)" diff --git a/Documentation/building/windows-instructions.md b/Documentation/building/windows-instructions.md index ba6bf631a799..ba46273e780a 100644 --- a/Documentation/building/windows-instructions.md +++ b/Documentation/building/windows-instructions.md @@ -8,7 +8,7 @@ Building CoreFX on Windows ## Recommended Software 1. **[Visual Studio 2019 Preview](https://visualstudio.microsoft.com/vs/preview/)** (Community, Professional, Enterprise) with the latest update should be installed. The Community version is completely free. -1. **[.NET Core SDK](https://www.microsoft.com/net/download/windows)** >= v3.0.0-preview3 should be installed, which will add the `dotnet` toolchain to your path. +1. **[.NET Core SDK](https://dotnet.microsoft.com/download/dotnet-core/3.0)** >= v3.0.0-preview3 should be installed, which will add the `dotnet` toolchain to your path. ### Visual Studio 2019 diff --git a/Documentation/debugging/unix-instructions.md b/Documentation/debugging/unix-instructions.md index 20d37c820357..33c89819b54c 100644 --- a/Documentation/debugging/unix-instructions.md +++ b/Documentation/debugging/unix-instructions.md @@ -33,7 +33,6 @@ It is also possible to debug .NET Core crash dumps using lldb and SOS. In order - Matching coreclr/corefx runtime bits from the crash. To get these, you should either: - Download the matching Jenkins archive onto your repro machine. - Check out the coreclr and corefx repositories at the appropriate commit and re-build the necessary portions. - - You can also download the matching "symbols" nuget package from myget.org. There is a "Download Symbols" button in the myget UI for this purpose. - lldb version 3.9. The SOS plugin (i.e. libsosplugin.so) provided is now built for lldb 3.9. In order to install lldb 3.9 just run the following commands: ``` ~$ echo "deb http://llvm.org/apt/trusty/ llvm-toolchain-trusty-3.9 main" | sudo tee /etc/apt/sources.list.d/llvm.list diff --git a/Documentation/project-docs/developer-guide.md b/Documentation/project-docs/developer-guide.md index febf112fca1c..e1c9511aefa7 100644 --- a/Documentation/project-docs/developer-guide.md +++ b/Documentation/project-docs/developer-guide.md @@ -8,7 +8,7 @@ The repo can be built for the following platforms, using the provided setup and | x64 | ✔ | ✔ | ✔ | ✔ | | x86 | ✔ | | | | | ARM | ✔ | ✔ | | | -| ARM64 | | ✔ | | | +| ARM64 | ✔ | ✔ | | | | | [Instructions](../building/windows-instructions.md) | [Instructions](../building/unix-instructions.md) | [Instructions](../building/unix-instructions.md) | [Instructions](../building/unix-instructions.md) | @@ -266,11 +266,11 @@ The tests can also be filtered based on xunit trait attributes defined in [`Micr ```cs [OuterLoop()] ``` -Tests marked as `OuterLoop` are for scenarios that don't need to run every build. They may take longer than normal tests, cover seldom hit code paths, or require special setup or resources to execute. These tests are excluded by default when testing through `dotnet msbuild` but can be enabled manually by adding the `-outerloop` switch or `/p:OuterLoop=true` e.g. +Tests marked as `OuterLoop` are for scenarios that don't need to run every build. They may take longer than normal tests, cover seldom hit code paths, or require special setup or resources to execute. These tests are excluded by default when testing through `dotnet msbuild` but can be enabled manually by adding the `-testscope outerloop` switch or `/p:TestScope=outerloop` e.g. ```cmd -build -test -outerloop -cd src/System.Text.RegularExpressions/tests && dotnet msbuild /t:RebuildAndTest /p:OuterLoop=true +build -test -testscope outerloop +cd src/System.Text.RegularExpressions/tests && dotnet msbuild /t:RebuildAndTest /p:TestScope=outerloop ``` #### PlatformSpecificAttribute diff --git a/Documentation/project-docs/dogfooding.md b/Documentation/project-docs/dogfooding.md index fffc61f88578..0a771def3d6b 100644 --- a/Documentation/project-docs/dogfooding.md +++ b/Documentation/project-docs/dogfooding.md @@ -47,7 +47,7 @@ To install additional .NET Core runtimes or SDKs: 4. Our nightly builds are uploaded to MyGet, not NuGet - so ensure the .NET Core MyGet feed is in your nuget configuration in case you need other packages from .NET Core that aren't included in the download. For example, on Windows you could edit `%userprofile%\appdata\roaming\nuget\nuget.config` or on Linux edit `~/.nuget/NuGet/NuGet.Config` to add this line: ```xml - + ... ``` @@ -118,7 +118,7 @@ make it self-contained Exe netcoreapp3.0 - + 3.0.0-preview-27218-01 win-x64 @@ -167,13 +167,13 @@ Note these instructions above were only about updates to the binaries that are p By default the dogfooding dotnet SDK will create a Nuget.Config file next to your project, if it doesn't you can create one. Your config file will need a source for your local corefx package directory as well -as a reference to our nightly dotnet-core feed on myget. The Nuget.Config file content should be: +as a reference to our nightly dotnet-core blob feed. The Nuget.Config file content should be: ```xml - + ``` diff --git a/Documentation/project-docs/issue-guide.md b/Documentation/project-docs/issue-guide.md index 4c99053dfc07..945d69044bc5 100644 --- a/Documentation/project-docs/issue-guide.md +++ b/Documentation/project-docs/issue-guide.md @@ -42,7 +42,7 @@ Areas are tracked by labels area-* (e.g. area-System.Collections). Each area |-----------------------------------------------------------------------------------------------|------------------|-------------| | [area-Infrastructure](https://github.com/dotnet/corefx/labels/area-Infrastructure) | [@ericstj](https://github.com/ericstj), [@karelz](https://github.com/karelz), [@wtgodbe](https://github.com/wtgodbe) | Covers:
  • Packaging
  • Build and test infra for CoreFX repo
  • VS integration

| | [area-Meta](https://github.com/dotnet/corefx/labels/area-Meta) | [@joperezr](https://github.com/joperezr) | Issues without clear association to any specific API/contract, e.g.
  • new contract proposals
  • cross-cutting code/test pattern changes (e.g. FxCop failures)
  • project-wide docs

| -| [area-Serialization](https://github.com/dotnet/corefx/labels/area-Serialization) | [@huanwu](https://github.com/huanwu), [@Lxiamail](https://github.com/Lxiamail), [@zhenlan](https://github.com/zhenlan) | Packages:
  • System.Runtime.Serialization.Xml
  • System.Runtime.Serialization.Json
  • System.Private.DataContractSerialization
  • System.Xml.XmlSerializer
Excluded:
  • System.Runtime.Serialization.Formatters
| +| [area-Serialization](https://github.com/dotnet/corefx/labels/area-Serialization) | [StephenMolloy](https://github.com/StephenMolloy), [@HongGit](https://github.com/HongGit) | Packages:
  • System.Runtime.Serialization.Xml
  • System.Runtime.Serialization.Json
  • System.Private.DataContractSerialization
  • System.Xml.XmlSerializer
Excluded:
  • System.Runtime.Serialization.Formatters
| | **System contract assemblies** | | | | [System.AppContext](https://github.com/dotnet/corefx/labels/area-System.AppContext) | **[@safern](https://github.com/safern)**, [@Anipik](https://github.com/Anipik) | | | | [System.Buffers](https://github.com/dotnet/corefx/labels/area-System.Buffers) | **[@layomia](https://github.com/layomia)**, [@JeremyKuhne](https://github.com/JeremyKuhne), [@ahsonkhan](https://github.com/ahsonkhan) | | @@ -53,8 +53,8 @@ Areas are tracked by labels area-* (e.g. area-System.Collections). Each area | [System.Composition](https://github.com/dotnet/corefx/labels/area-System.Composition) | **[@maryamariyan](https://github.com/maryamariyan)**, [@ViktorHofer](https://github.com/ViktorHofer) | | | [System.Configuration](https://github.com/dotnet/corefx/labels/area-System.Configuration) | **[@maryamariyan](https://github.com/maryamariyan)**, [@safern](https://github.com/safern) | | | [System.Console](https://github.com/dotnet/corefx/labels/area-System.Console) | [@wtgodbe](https://github.com/wtgodbe) | | -| [System.Data](https://github.com/dotnet/corefx/labels/area-System.Data) | **[@divega](https://github.com/divega)**, [@ajcvickers](https://github.com/ajcvickers), [@afsanehr](https://github.com/afsanehr), [@david-engel](https://github.com/david-engel), [@tarikulsabbir](https://github.com/tarikulsabbir), [@Gary-Zh ](https://github.com/Gary-Zh) | | -| [System.Data.SqlClient](https://github.com/dotnet/corefx/labels/area-System.Data.SqlClient) | **[@afsanehr](https://github.com/afsanehr)**, [@tarikulsabbir](https://github.com/tarikulsabbir), [@Gary-Zh ](https://github.com/Gary-Zh), [@david-engel](https://github.com/david-engel) | | +| [System.Data](https://github.com/dotnet/corefx/labels/area-System.Data) | **[@divega](https://github.com/divega)**, [@ajcvickers](https://github.com/ajcvickers), [@afsanehr](https://github.com/afsanehr), [@david-engel](https://github.com/david-engel), [@Gary-Zh ](https://github.com/Gary-Zh) |
  • Odbc, OleDb - [@saurabh](https://github.com/saurabh)
| +| [System.Data.SqlClient](https://github.com/dotnet/corefx/labels/area-System.Data.SqlClient) | **[@afsanehr](https://github.com/afsanehr)**, [@Gary-Zh ](https://github.com/Gary-Zh), [@david-engel](https://github.com/david-engel) | | | [System.Diagnostics](https://github.com/dotnet/corefx/labels/area-System.Diagnostics) | **[@wtgodbe](https://github.com/wtgodbe)**, [@krwq](https://github.com/krwq) |
  • System.Diagnostics.EventLog - [@Anipik](https://github.com/Anipik)
| | [System.Diagnostics.Process](https://github.com/dotnet/corefx/labels/area-System.Diagnostics.Process) | **[@wtgodbe](https://github.com/wtgodbe)**, [@krwq](https://github.com/krwq) | | | [System.Diagnostics.Tracing](https://github.com/dotnet/corefx/labels/area-System.Diagnostics.Tracing) | [@noahfalk](https://github.com/noahfalk), [@tommcdon](https://github.com/tommcdon), [@Anipik](https://github.com/Anipik) | Packages:
  • System.Diagnostics.DiagnosticSource
  • System.Diagnostics.PerformanceCounter - [@Anipik](https://github.com/Anipik)
  • System.Diagnostics.Tracing
  • System.Diagnostics.TraceSource - [@Anipik](https://github.com/Anipik)

| @@ -62,19 +62,20 @@ Areas are tracked by labels area-* (e.g. area-System.Collections). Each area | [System.Drawing](https://github.com/dotnet/corefx/labels/area-System.Drawing) | **[@safern](https://github.com/safern)**, [@maryamariyan](https://github.com/maryamariyan) | | | [System.Dynamic.Runtime](https://github.com/dotnet/corefx/labels/area-System.Dynamic.Runtime) | [@cston](https://github.com/cston), [@333fred](https://github.com/333fred) | Archived component - limited churn/contributions (see [#33170](https://github.com/dotnet/corefx/issues/33170)) | | [System.Globalization](https://github.com/dotnet/corefx/labels/area-System.Globalization) | **[@krwq](https://github.com/krwq)**, [@tarekgh](https://github.com/tarekgh) | | -| [System.IO](https://github.com/dotnet/corefx/labels/area-System.IO) | [@JeremyKuhne](https://github.com/JeremyKuhne) | | -| [System.IO.Compression](https://github.com/dotnet/corefx/labels/area-System.IO.Compression) | **[@buyaa-n](https://github.com/buyaa-n)**, [@ahsonkhan](https://github.com/ahsonkhan), [@ViktorHofer](https://github.com/ViktorHofer) | | -| [System.IO.Pipelines](https://github.com/dotnet/corefx/labels/area-System.IO.Pipelines) | **[@pakrym](https://github.com/pakrym)**, [@davidfowl](https://github.com/davidfowl) | | +| [System.IO](https://github.com/dotnet/corefx/labels/area-System.IO) | **[@JeremyKuhne](https://github.com/JeremyKuhne)**, [@carlossanlop](https://github.com/carlossanlop) | | +| [System.IO.Compression](https://github.com/dotnet/corefx/labels/area-System.IO.Compression) | **[@carlossanlop](https://github.com/carlossanlop)**, [@ahsonkhan](https://github.com/ahsonkhan), [@ViktorHofer](https://github.com/ViktorHofer) | | +| [System.IO.Packaging](https://github.com/dotnet/corefx/labels/area-System.IO.Packaging) | [@JeremyKuhne](https://github.com/JeremyKuhne) | | +| [System.IO.Pipelines](https://github.com/dotnet/corefx/labels/area-System.IO.Pipelines) | [@davidfowl](https://github.com/davidfowl), [@halter73](https://github.com/halter73), [@jkotalik](https://github.com/jkotalik), [@anurse](https://github.com/anurse) | | | [System.Linq](https://github.com/dotnet/corefx/labels/area-System.Linq) | [@maryamariyan](https://github.com/maryamariyan) | | | [System.Linq.Expressions](https://github.com/dotnet/corefx/labels/area-System.Linq.Expressions) | [@cston](https://github.com/cston), [@333fred](https://github.com/333fred) | Archived component - limited churn/contributions (see [#33170](https://github.com/dotnet/corefx/issues/33170)) | | [System.Linq.Parallel](https://github.com/dotnet/corefx/labels/area-System.Linq.Parallel) | **[@tarekgh](https://github.com/tarekgh)**, [@kouvel](https://github.com/kouvel) | | | [System.Management](https://github.com/dotnet/corefx/labels/area-System.Management) | [@Anipik](https://github.com/Anipik) | WMI | | [System.Memory](https://github.com/dotnet/corefx/labels/area-System.Memory) | [@ahsonkhan](https://github.com/ahsonkhan) | | -| [System.Net](https://github.com/dotnet/corefx/labels/area-System.Net) | [@davidsh](https://github.com/davidsh), [@wfurt](https://github.com/wfurt), [@karelz](https://github.com/karelz) | Included:
  • System.Uri - [@wtgodbe](https://github.com/wtgodbe)
| -| [System.Net.Http](https://github.com/dotnet/corefx/labels/area-System.Net.Http) | [@davidsh](https://github.com/davidsh), [@wfurt](https://github.com/wfurt), [@karelz](https://github.com/karelz) | | -| [System.Net.Http.SocketsHttpHandler](https://github.com/dotnet/corefx/labels/area-System.Net.Http.SocketsHttpHandler) | [@geoffkizer](https://github.com/geoffkizer), [@wfurt](https://github.com/wfurt), [@davidsh](https://github.com/davidsh), [@karelz](https://github.com/karelz) | | -| [System.Net.Security](https://github.com/dotnet/corefx/labels/area-System.Net.Security) | [@davidsh](https://github.com/davidsh), [@wfurt](https://github.com/wfurt), [@karelz](https://github.com/karelz) | | -| [System.Net.Sockets](https://github.com/dotnet/corefx/labels/area-System.Net.Sockets) | [@davidsh](https://github.com/davidsh), [@wfurt](https://github.com/wfurt), [@karelz](https://github.com/karelz) | | +| [System.Net](https://github.com/dotnet/corefx/labels/area-System.Net) | [@davidsh](https://github.com/davidsh), [@wfurt](https://github.com/wfurt), [@scalablecory](https://github.com/scalablecory), [@karelz](https://github.com/karelz) | Included:
  • System.Uri - [@wtgodbe](https://github.com/wtgodbe)
| +| [System.Net.Http](https://github.com/dotnet/corefx/labels/area-System.Net.Http) | [@davidsh](https://github.com/davidsh), [@wfurt](https://github.com/wfurt), [@scalablecory](https://github.com/scalablecory), [@karelz](https://github.com/karelz) | | +| [System.Net.Http.SocketsHttpHandler](https://github.com/dotnet/corefx/labels/area-System.Net.Http.SocketsHttpHandler) | [@geoffkizer](https://github.com/geoffkizer), [@wfurt](https://github.com/wfurt), [@davidsh](https://github.com/davidsh), [@scalablecory](https://github.com/scalablecory), [@karelz](https://github.com/karelz) | | +| [System.Net.Security](https://github.com/dotnet/corefx/labels/area-System.Net.Security) | [@davidsh](https://github.com/davidsh), [@wfurt](https://github.com/wfurt), [@scalablecory](https://github.com/scalablecory), [@karelz](https://github.com/karelz) | | +| [System.Net.Sockets](https://github.com/dotnet/corefx/labels/area-System.Net.Sockets) | [@davidsh](https://github.com/davidsh), [@wfurt](https://github.com/wfurt), [@scalablecory](https://github.com/scalablecory), [@karelz](https://github.com/karelz) | | | [System.Numerics](https://github.com/dotnet/corefx/labels/area-System.Numerics) | [@tannergooding](https://github.com/tannergooding), [@ViktorHofer](https://github.com/ViktorHofer) | | | [System.Numerics.Tensors](https://github.com/dotnet/corefx/labels/area-System.Numerics.Tensors) | [@tannergooding](https://github.com/tannergooding) | | | [System.Reflection](https://github.com/dotnet/corefx/labels/area-System.Reflection) | [@steveharter](https://github.com/steveharter), [@GrabYourPitchforks](https://github.com/GrabYourPitchforks) | | @@ -82,14 +83,14 @@ Areas are tracked by labels area-* (e.g. area-System.Collections). Each area | [System.Reflection.Metadata](https://github.com/dotnet/corefx/labels/area-System.Reflection.Metadata) | [@tmat](https://github.com/tmat), [@nguerrera](https://github.com/nguerrera) | | | [System.Resources](https://github.com/dotnet/corefx/labels/area-System.Resources) | **[@krwq](https://github.com/krwq)**, [@tarekgh](https://github.com/tarekgh) | | | [System.Runtime](https://github.com/dotnet/corefx/labels/area-System.Runtime) | **[@bartonjs](https://github.com/bartonjs)**, [@joperezr](https://github.com/joperezr) | Included:
  • System.Runtime.Serialization.Formatters
  • System.Runtime.InteropServices.RuntimeInfo
  • System.Array
Excluded:
  • Path -> System.IO
  • StopWatch -> System.Diagnostics
  • Uri -> System.Net
  • WebUtility -> System.Net
| -| [System.Runtime.Caching](https://github.com/dotnet/corefx/labels/area-System.Runtime.Caching) | [@KKhurin](https://github.com/KKhurin), [@Lxiamail](https://github.com/Lxiamail), [@zhenlan](https://github.com/zhenlan) | | +| [System.Runtime.Caching](https://github.com/dotnet/corefx/labels/area-System.Runtime.Caching) | [@KKhurin](https://github.com/KKhurin), [@HongGit](https://github.com/HongGit) | | | [System.Runtime.CompilerServices](https://github.com/dotnet/corefx/labels/area-System.Runtime.CompilerServices) | [@Anipik](https://github.com/Anipik) | | | [System.Runtime.Extensions](https://github.com/dotnet/corefx/labels/area-System.Runtime.Extensions) | [@Anipik](https://github.com/Anipik) | | | [System.Runtime.InteropServices](https://github.com/dotnet/corefx/labels/area-System.Runtime.InteropServices) | [@AaronRobinsonMSFT](https://github.com/AaronRobinsonMSFT), [@jkoritzinsky](https://github.com/jkoritzinsky) | Excluded:
  • System.Runtime.InteropServices.RuntimeInfo
| | [System.Runtime.Intrinsics](https://github.com/dotnet/corefx/labels/area-System.Runtime.Intrinsics) | [@tannergooding](https://github.com/tannergooding), [@CarolEidt](https://github.com/CarolEidt), [@RussKeldorph](https://github.com/RussKeldorph) | | | [System.Security](https://github.com/dotnet/corefx/labels/area-System.Security) | **[@bartonjs](https://github.com/bartonjs)**, [@GrabYourPitchforks](https://github.com/GrabYourPitchforks) | | | System.ServiceModel | N/A | [dotnet/wcf](https://github.com/dotnet/wcf) (except System.ServiceModel.Syndication) | -| [System.ServiceModel.Syndication](https://github.com/dotnet/corefx/labels/area-System.ServiceModel.Syndication) | [@huanwu](https://github.com/huanwu), [@Lxiamail](https://github.com/Lxiamail), [@zhenlan](https://github.com/zhenlan) | | +| [System.ServiceModel.Syndication](https://github.com/dotnet/corefx/labels/area-System.ServiceModel.Syndication) | [StephenMolloy](https://github.com/StephenMolloy), [@HongGit](https://github.com/HongGit) | | | [System.ServiceProcess](https://github.com/dotnet/corefx/labels/area-System.ServiceProcess) | **[@maryamariyan](https://github.com/maryamariyan)**, [@Anipik](https://github.com/Anipik) | | | [System.Text.Encoding](https://github.com/dotnet/corefx/labels/area-System.Text.Encoding) | **[@layomia](https://github.com/layomia)**, [@krwq](https://github.com/krwq), [@tarekgh](https://github.com/tarekgh) | | | [System.Text.Encodings.Web](https://github.com/dotnet/corefx/labels/area-System.Text.Encodings.Web) | **[@GrabYourPitchforks](https://github.com/GrabYourPitchforks)**, [@layomia](https://github.com/layomia), [@tarekgh](https://github.com/tarekgh) | | diff --git a/Documentation/project-docs/pullrequest-builds.md b/Documentation/project-docs/pullrequest-builds.md index e46818274e41..ebda7c343c4c 100644 --- a/Documentation/project-docs/pullrequest-builds.md +++ b/Documentation/project-docs/pullrequest-builds.md @@ -15,7 +15,7 @@ As part of our Pull Requests we have some validation builds where we build the p | Linux arm64_Release | netcoreapp | X | X | | Linux arm_Release | netcoreapp | X | | | Linux musl_x64_Debug | netcoreapp | X | | -| MacOS x64_Debug | netcoreapp | X | | +| MacOS x64_Debug | netcoreapp | X | X | | Packaging All Configurations x64_Debug | all | X | X | Our build definitions are defined by some `.yml` files with the following structure: @@ -58,12 +58,7 @@ Once in the build UI you can look at a specific job, or step log, by clicking on ## How to look at a test failure -Currently, our test results are exposed by https://mc.dot.net/ as we wait for new features by Azure DevOps to use their text explorer. In order to get to the test results, you need to click on the `Send to Helix` step on a job, and within its logs, there will be a text containing the test results URL, which you can `CTRL+Click` to open. It will look like the following: -``` -Results will be available from https://mc.dot.net/#/user/dotnet-bot/pr~2Fdotnet~2Fcorefx~2Frefs~2Fpull~2F35667~2Fmerge/test~2Ffunctional~2Fcli~2F/20190228.23 -``` - -Then on Mission Control, you can just navigate through the results and look at stack traces, and detailed logs. +Use the Azure DevOps Test Explorer which lists all tests grouped by the different build configurations. You can filter and navigate through the results and look at stack traces, and detailed logs. ## How to rerun builds @@ -91,4 +86,4 @@ Once you click under the `Artifacts` section, a popup will show, with multiple d 7. Only an entire pipeline can be triggered through comments, triggering a single leg is not supported yet. `/azp run corefx-ci (macOS x64_Debug)` wouldn't work. 8. Rerunning a single leg while others are still running is not yet supported, you have to wait for all legs to finish before retrying an individual leg. -All of this issues have been raised to Azure DevOps teams, expect @safern, to update the docs through PR to widely communicate new features coming. \ No newline at end of file +All of this issues have been raised to Azure DevOps teams, expect @safern, to update the docs through PR to widely communicate new features coming. diff --git a/README.md b/README.md index dac3e2e16202..26b6a118994c 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,12 @@ Runtime-specific library code ([System.Private.CoreLib](https://github.com/dotne ## .NET Core -Official Starting Page: https://dotnet.github.io +Official Starting Page: https://dotnet.microsoft.com/ -* [How to use .NET Core](https://github.com/dotnet/core/#get-started) (with VS, VS Code, command-line CLI) - * [Install official releases](https://www.microsoft.com/net/core) - * [Documentation](https://docs.microsoft.com/en-us/dotnet) (Get Started, Tutorials, Porting from .NET Framework, API reference, ...) - * [Deploying apps](https://docs.microsoft.com/en-us/dotnet/core/deploying) +* [How to use .NET Core](https://docs.microsoft.com/dotnet/core/get-started) (with VS, VS Code, command-line CLI) + * [Install official releases](https://dotnet.microsoft.com/download) + * [Documentation](https://docs.microsoft.com/dotnet/core) (Get Started, Tutorials, Porting from .NET Framework, API reference, ...) + * [Deploying apps](https://docs.microsoft.com/dotnet/core/deploying) * [Supported OS versions](https://github.com/dotnet/core/blob/master/os-lifecycle-policy.md) * [Roadmap](https://github.com/dotnet/core/blob/master/roadmap.md) * [Releases](https://github.com/dotnet/core/tree/master/release-notes) @@ -45,8 +45,9 @@ This section is **in progress** here: [New contributor Docs - Contributing](http ### Useful Links * [.NET Core source index](https://source.dot.net) / [.NET Framework source index](https://referencesource.microsoft.com) -* [API Reference docs](https://docs.microsoft.com/en-us/dotnet/core/api) +* [API Reference docs](https://docs.microsoft.com/dotnet/api/?view=netcore-3.0) * [.NET API Catalog](http://apisof.net) (incl. APIs from daily builds and API usage info) +* [API docs writing guidelines](https://github.com/dotnet/dotnet-api-docs/wiki) - useful when writing /// comments ### Community @@ -83,7 +84,8 @@ There are many .NET related projects on GitHub. ### Daily Builds -Daily builds of .NET Core components are published to [dotnet-core MyGet gallery](https://dotnet.myget.org/gallery/dotnet-core). -The latest version number of each library can be seen in that gallery. +Daily builds of .NET Core components are published to dotnet-blob feed (https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json). +The latest version number of each library can be seen in that feed. +Currently, there is no website to visualize the contents of the feed, so in order to do so, you have to use a NuGet feed explorer, like Visual Studio. Note: See officially supported [OS versions](https://github.com/dotnet/core/blob/master/os-lifecycle-policy.md). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000000..92d052767fc0 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,15 @@ +# Security Policy + +## Supported Versions + +The .NET Core and ASP.NET Core support policy, including supported versions can be found at the [.NET Core Support Policy Page](https://dotnet.microsoft.com/platform/support/policy/dotnet-core). + +## Reporting a Vulnerability + +Security issues and bugs should be reported privately, via email, to the Microsoft Security Response Center (MSRC) secure@microsoft.com. +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your +original message. Further information, including the MSRC PGP key, can be found in the [Security TechCenter](https://technet.microsoft.com/en-us/security/ff852094.aspx). + +Reports via MSRC may qualify for the .NET Core Bug Bounty. Details of the .NET Core Bug Bounty including terms and conditions are at [https://aka.ms/corebounty](https://aka.ms/corebounty). + +Please do not open issues for anything you think might have a security implication. diff --git a/THIRD-PARTY-NOTICES.TXT b/THIRD-PARTY-NOTICES.TXT index b25636f506b8..de86db916f79 100644 --- a/THIRD-PARTY-NOTICES.TXT +++ b/THIRD-PARTY-NOTICES.TXT @@ -332,3 +332,35 @@ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for vectorized base64 encoding / decoding +-------------------------------------------------------- + +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2016-2017, Matthieu Darbois +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/build.proj b/build.proj index 9583b0d4c2e4..d881d293f38a 100644 --- a/build.proj +++ b/build.proj @@ -26,14 +26,6 @@ - - - - <_ValidProjectsForRestore Include="$(MSBuildProjectFullPath)" /> - - - <_BuildNativeProjects Include="src\Native\build-native.proj" /> @@ -114,7 +106,8 @@ - + <_solutionsToUpdateFiles Include="$(MSBuildThisFileDirectory)src/*/Directory.Build.props" /> diff --git a/eng/Build.props b/eng/Build.props index 71feaecf8884..e44e41b604cb 100644 --- a/eng/Build.props +++ b/eng/Build.props @@ -1,7 +1,4 @@ - - false - diff --git a/eng/DefaultGenApiDocIds.txt b/eng/DefaultGenApiDocIds.txt index aab2ef4ec82b..c0649f4f6c61 100644 --- a/eng/DefaultGenApiDocIds.txt +++ b/eng/DefaultGenApiDocIds.txt @@ -20,16 +20,17 @@ T:System.IO.IODescriptionAttribute T:System.Runtime.CompilerServices.AsyncStateMachineAttribute T:System.Runtime.CompilerServices.CompilerGeneratedAttribute T:System.Runtime.CompilerServices.IteratorStateMachineAttribute -T:System.Runtime.CompilerServices.TypeForwardedFromAttribute T:System.Runtime.CompilerServices.MethodImpl +T:System.Runtime.CompilerServices.NullableAttribute +T:System.Runtime.CompilerServices.TypeForwardedFromAttribute T:System.Runtime.ConstrainedExecution.ReliabilityContractAttribute T:System.Runtime.InteropServices.ClassInterfaceAttribute T:System.Runtime.InteropServices.ComDefaultInterfaceAttribute T:System.Runtime.InteropServices.ComVisibleAttribute T:System.Runtime.InteropServices.GuidAttribute T:System.Runtime.InteropServices.InterfaceTypeAttribute +T:System.Runtime.InteropServices.LCIDConversionAttribute T:System.Runtime.InteropServices.StructLayoutAttribute -T:System.Runtime.Serialization.KnownTypeAttribute T:System.Security.Permissions.EnvironmentPermissionAttribute T:System.Security.Permissions.FileIOPermissionAttribute T:System.Security.Permissions.HostProtectionAttribute @@ -41,10 +42,6 @@ T:System.Security.Permissions.StrongNameIdentityPermissionAttribute T:System.Security.SecurityCriticalAttribute T:System.Security.SecuritySafeCriticalAttribute T:System.Security.SuppressUnmanagedCodeSecurityAttribute -T:System.Xml.Serialization.XmlAttributeAttribute -T:System.Xml.Serialization.XmlEnumAttribute -T:System.Xml.Serialization.XmlIgnoreAttribute -T:System.Xml.Serialization.XmlRootAttribute T:System.Runtime.Versioning.NonVersionableAttribute T:System.Runtime.CompilerServices.IntrinsicAttribute T:System.Runtime.CompilerServices.ExtensionAttribute diff --git a/eng/InternalTools.props b/eng/InternalTools.props deleted file mode 100644 index b16d4b44460d..000000000000 --- a/eng/InternalTools.props +++ /dev/null @@ -1,22 +0,0 @@ - - - - - true - - - - - - - - - - - - - https://dnceng.pkgs.visualstudio.com/_packaging/dotnet-internal/nuget/v3/index.json; - $(RestoreSources); - - - diff --git a/eng/Packaging.props b/eng/Packaging.props index b87e77a0a347..e0db02c6cbf2 100644 --- a/eng/Packaging.props +++ b/eng/Packaging.props @@ -14,7 +14,7 @@ Microsoft.Private.Intellisense 3.0.0-preview3-190305-0 - $(PackagesDir)$(XmlDocPackage.ToLowerInvariant())/$(XmlDocPackageVersion)/xmldocs/netcoreapp + $(NuGetPackageRoot)$(XmlDocPackage.ToLowerInvariant())/$(XmlDocPackageVersion)/xmldocs/netcoreapp $(ArtifactsBinDir)docs - $(NoWarn);0169;0649 + $(NoWarn);CS0169;CS0649;CS8618 + + + $(NoWarn);CS8597 + + + $(NoWarn);CS8625 diff --git a/eng/Tools.props b/eng/Tools.props index 6cd5fb9f7829..2508e08626a5 100644 --- a/eng/Tools.props +++ b/eng/Tools.props @@ -3,6 +3,7 @@ https://dotnet.myget.org/F/dotnet-buildtools/api/v3/index.json; https://dotnet.myget.org/F/sourcelink/api/v3/index.json; + $(OverridePackageSource); $(RestoreSources) false @@ -10,11 +11,6 @@ $(ArtifactsToolsetDir)Common\Tools.Analyzers.props - - $([MSBuild]::NormalizeDirectory('$(RepoRoot)', '.dotnet')) - $(DotNetRoot)dotnet - $(DotNetCmd).exe - "$(DotNetCmd)" @@ -22,15 +18,10 @@ - - - - - @@ -39,6 +30,11 @@ + + + + + @@ -53,73 +49,8 @@ - - - - - - - - - $([MSBuild]::NormalizeDirectory('$(RepoRoot)', '.tools', 'CredentialsProvider')) - https://raw.githubusercontent.com/Microsoft/artifacts-credprovider/master/helpers/installcredprovider.ps1 - https://raw.githubusercontent.com/Microsoft/artifacts-credprovider/master/helpers/installcredprovider.sh - - - - - - - - - - - $([MSBuild]::NormalizeDirectory('$(RepositoryEngineeringDir)', 'common', 'internal')) - $(OptionalToolDir)Tools.csproj - - - - - - - - - - - $([MSBuild]::NormalizePath('$(RepoRoot)', '.tools', 'globaltools')) - - - - - - - - - - - - - - - - + https://github.com/dotnet/coreclr - e330c2ce5b1af4e69cdcacb8254a5107586c68f8 + fa8383fb28be945cae900a5579afd5920f274fd4 - + https://github.com/dotnet/coreclr - e330c2ce5b1af4e69cdcacb8254a5107586c68f8 + fa8383fb28be945cae900a5579afd5920f274fd4 - + https://github.com/dotnet/coreclr - e330c2ce5b1af4e69cdcacb8254a5107586c68f8 + fa8383fb28be945cae900a5579afd5920f274fd4 - + https://github.com/dotnet/core-setup - 3907f75cb6a0489f8dc6f72169146c3d79d20d41 + 63abc77da6d99470caa5bfa0465afe244105e595 - + https://github.com/dotnet/core-setup - 3907f75cb6a0489f8dc6f72169146c3d79d20d41 + 63abc77da6d99470caa5bfa0465afe244105e595 - + https://github.com/dotnet/core-setup - 3907f75cb6a0489f8dc6f72169146c3d79d20d41 + 63abc77da6d99470caa5bfa0465afe244105e595 - + https://github.com/dotnet/corefx - 8b515adcd4ea0b8233f018f9e87ef946ce0e7c42 + 82408cd90f4d4573d502e8df2ca437b35e6a37f7 - + + https://github.com/dotnet/corefx + 82408cd90f4d4573d502e8df2ca437b35e6a37f7 + + https://github.com/dotnet/arcade - 5e7ce5b394f3477bb0a485a4b761b7742e95be37 + 7c50d548001a83a18449ad4dda370122ede5fbf6 - + https://github.com/dotnet/standard - 5eee83eaa61eff38f470dc690218bebf73f46e23 - - - https://github.com/dotnet/arcade - bda52d7619f9420de46f2c39ffc972864bbcab63 + 4d364ea4ecaf4d5da8d6f969f70db753dcc614b0 - + https://github.com/dotnet/arcade - 5e7ce5b394f3477bb0a485a4b761b7742e95be37 + 7c50d548001a83a18449ad4dda370122ede5fbf6 - + https://github.com/dotnet/arcade - 5e7ce5b394f3477bb0a485a4b761b7742e95be37 + 7c50d548001a83a18449ad4dda370122ede5fbf6 - + https://github.com/dotnet/arcade - 5e7ce5b394f3477bb0a485a4b761b7742e95be37 + 7c50d548001a83a18449ad4dda370122ede5fbf6 - + https://github.com/dotnet/arcade - 5e7ce5b394f3477bb0a485a4b761b7742e95be37 + 7c50d548001a83a18449ad4dda370122ede5fbf6 - + https://github.com/dotnet/arcade - 5e7ce5b394f3477bb0a485a4b761b7742e95be37 + 7c50d548001a83a18449ad4dda370122ede5fbf6 - + https://github.com/dotnet/arcade - 5e7ce5b394f3477bb0a485a4b761b7742e95be37 + 7c50d548001a83a18449ad4dda370122ede5fbf6 - + https://github.com/dotnet/arcade - 5e7ce5b394f3477bb0a485a4b761b7742e95be37 + 7c50d548001a83a18449ad4dda370122ede5fbf6 - + https://github.com/dotnet/arcade - 5e7ce5b394f3477bb0a485a4b761b7742e95be37 + 7c50d548001a83a18449ad4dda370122ede5fbf6 - + https://github.com/dotnet/arcade - 5e7ce5b394f3477bb0a485a4b761b7742e95be37 + 7c50d548001a83a18449ad4dda370122ede5fbf6 - + https://github.com/dotnet/arcade - 5e7ce5b394f3477bb0a485a4b761b7742e95be37 + 7c50d548001a83a18449ad4dda370122ede5fbf6 - + https://github.com/dotnet/arcade - 5e7ce5b394f3477bb0a485a4b761b7742e95be37 + 7c50d548001a83a18449ad4dda370122ede5fbf6 - + https://github.com/dotnet/arcade - 5e7ce5b394f3477bb0a485a4b761b7742e95be37 + 7c50d548001a83a18449ad4dda370122ede5fbf6 - + https://github.com/dotnet/arcade - 5e7ce5b394f3477bb0a485a4b761b7742e95be37 + 7c50d548001a83a18449ad4dda370122ede5fbf6 - + https://dev.azure.com/dnceng/internal/_git/dotnet-optimization - f0801f43ca046737efb933d07b741838f5197e19 + 680817355bb2e1326de1124c846263f8d9fb9294 diff --git a/eng/Versions.props b/eng/Versions.props index 3308bded8da8..7d74ab0a8658 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -7,7 +7,7 @@ 7 true - preview5 + preview6 true true @@ -18,36 +18,52 @@ Microsoft.DotNet.XUnitExtensions microsoft.dotnet.xunitconsolerunner - Microsoft.DotNet.RemoteExecutor + microsoft.dotnet.remoteexecutor NETStandard.Library - 1.0.0-beta.19218.7 - 1.0.0-beta.19218.7 - 1.0.0-beta.19218.7 - 1.0.0-beta.19218.7 - 1.0.0-beta.19218.7 - 2.4.0-beta.19218.7 - 2.5.1-beta.19218.7 - 1.0.0-beta.19218.7 - 1.0.0-beta.19218.7 - 1.0.0-beta.19218.7 - 1.0.0-beta.19218.7 - 2.2.0-beta.19218.7 - 1.0.0-beta.19218.7 + 1.0.0-beta.19280.2 + 1.0.0-beta.19280.2 + 1.0.0-beta.19280.2 + 1.0.0-beta.19280.2 + 2.4.1-beta.19280.2 + 2.5.1-beta.19280.2 + 1.0.0-beta.19280.2 + 1.0.0-beta.19280.2 + 1.0.0-beta.19280.2 + 1.0.0-beta.19280.2 + 2.2.0-beta.19280.2 + 1.0.0-beta.19280.2 - 3.0.0-preview5-27620-10 - 3.0.0-preview5-27620-10 - 3.0.0-preview5-27620-10 + 3.0.0-preview6-27730-01 + 3.0.0-preview6-27730-01 + 3.0.0-preview6-27730-01 - 3.0.0-preview5-27708-72 - 3.0.0-preview5-27708-72 + 3.0.0-preview6.19280.2 + 3.0.0-preview6.19280.2 - 3.0.0-preview5.19220.3 + 3.0.0-preview6.19281.1 + 4.6.0-preview6.19281.1 - 2.1.0-prerelease.19222.1 + 2.1.0-prerelease.19281.2 - 99.99.99-master-20190421.1 + 99.99.99-master-20190521.3 + + 4.4.0 + 4.4.0 + + 16.0.1 + 2.4.1-pre.build.4059 + 2.0.5 + 1.0.31 + + 1.5.0 + 4.1.4 + + Microsoft.SymbolUploader.Build.Task + 1.0.0-beta-63604-05 + + diff --git a/eng/build.ps1 b/eng/build.ps1 index 09a3e5030a76..e459efa38805 100644 --- a/eng/build.ps1 +++ b/eng/build.ps1 @@ -1,13 +1,14 @@ [CmdletBinding(PositionalBinding=$false)] Param( [switch][Alias('b')]$build, + [switch][Alias('t')]$test, [switch] $buildtests, [string][Alias('c')]$configuration = "Debug", [string][Alias('f')]$framework, [string] $os, [switch] $allconfigurations, [switch] $coverage, - [switch] $outerloop, + [string] $testscope, [string] $arch, [switch] $clean, [Parameter(ValueFromRemainingArguments=$true)][String[]]$properties @@ -36,7 +37,7 @@ function Get-Help() { Write-Host "Advanced settings:" Write-Host " -coverage Collect code coverage when testing" - Write-Host " -outerloop Include tests which are marked as OuterLoop" + Write-Host " -testscope Scope tests, allowed values: innerloop, outerloop, all" Write-Host " -allconfigurations Build packages for all build configurations" Write-Host " -os Build operating system: Windows_NT or Unix" Write-Host " -arch Build platform: x86, x64, arm or arm64" @@ -93,6 +94,8 @@ foreach ($argument in $PSBoundParameters.Keys) { switch($argument) { + "build" { $arguments += " -build" } + "test" { $arguments += " -test" } "buildtests" { $arguments += " /p:BuildTests=true" } "clean" { } "configuration" { $configuration = (Get-Culture).TextInfo.ToTitleCase($($PSBoundParameters[$argument])); $arguments += " /p:ConfigurationGroup=$configuration -configuration $configuration" } @@ -100,7 +103,7 @@ foreach ($argument in $PSBoundParameters.Keys) "os" { $arguments += " /p:OSGroup=$($PSBoundParameters[$argument])" } "allconfigurations" { $arguments += " /p:BuildAllConfigurations=true" } "coverage" { $arguments += " /p:Coverage=true" } - "outerloop" { $arguments += " /p:OuterLoop=true" } + "testscope" { $arguments += " /p:TestScope=$($PSBoundParameters[$argument])" } "arch" { $arguments += " /p:ArchGroup=$($PSBoundParameters[$argument])" } "properties" { $arguments += " " + $properties } default { $arguments += " /p:$argument=$($PSBoundParameters[$argument])" } diff --git a/eng/build.sh b/eng/build.sh index a72e265d9733..1ba96ae25f40 100755 --- a/eng/build.sh +++ b/eng/build.sh @@ -36,7 +36,7 @@ usage() echo "Advanced settings:" echo " --coverage Collect code coverage when testing" - echo " --outerloop Include tests which are marked as OuterLoop" + echo " --testscope Test scope, allowed values: innerloop, outerloop, all" echo " --allconfigurations Build packages for all build configurations" echo " --os Build operating system: Windows_NT or Unix" echo " --arch Build platform: x86, x64, arm or arm64" @@ -100,9 +100,9 @@ while [[ $# > 0 ]]; do arguments="$arguments /p:BuildTests=true" shift 1 ;; - -outerloop) - arguments="$arguments /p:OuterLoop=true" - shift 1 + -testscope) + arguments="$arguments /p:TestScope=$2" + shift 2 ;; -coverage) arguments="$arguments /p:Coverage=true" diff --git a/eng/common/LoggingCommandFunctions.ps1 b/eng/common/LoggingCommandFunctions.ps1 new file mode 100644 index 000000000000..c225eaecbf25 --- /dev/null +++ b/eng/common/LoggingCommandFunctions.ps1 @@ -0,0 +1,146 @@ +# Source for this file was taken from https://github.com/microsoft/azure-pipelines-task-lib/blob/11c9439d4af17e6475d9fe058e6b2e03914d17e6/powershell/VstsTaskSdk/LoggingCommandFunctions.ps1 + +# NOTE: You should not be calling these method directly as they are likely to change. Instead you should be calling the Write-Pipeline* functions defined in tools.ps1 + +$script:loggingCommandPrefix = '##vso[' +$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"? + New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' } + New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' } + New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' } + New-Object psobject -Property @{ Token = "]" ; Replacement = '%5D' } +) +# TODO: BUG: Escape % ??? +# TODO: Add test to verify don't need to escape "=". + +<######################################## +# Private functions. +########################################> +function Format-LoggingCommandData { + [CmdletBinding()] + param([string]$Value, [switch]$Reverse) + + if (!$Value) { + return '' + } + + if (!$Reverse) { + foreach ($mapping in $script:loggingCommandEscapeMappings) { + $Value = $Value.Replace($mapping.Token, $mapping.Replacement) + } + } else { + for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) { + $mapping = $script:loggingCommandEscapeMappings[$i] + $Value = $Value.Replace($mapping.Replacement, $mapping.Token) + } + } + + return $Value +} + +function Format-LoggingCommand { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Area, + [Parameter(Mandatory = $true)] + [string]$Event, + [string]$Data, + [hashtable]$Properties) + + # Append the preamble. + [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder + $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event) + + # Append the properties. + if ($Properties) { + $first = $true + foreach ($key in $Properties.Keys) { + [string]$value = Format-LoggingCommandData $Properties[$key] + if ($value) { + if ($first) { + $null = $sb.Append(' ') + $first = $false + } else { + $null = $sb.Append(';') + } + + $null = $sb.Append("$key=$value") + } + } + } + + # Append the tail and output the value. + $Data = Format-LoggingCommandData $Data + $sb.Append(']').Append($Data).ToString() +} + +function Write-LoggingCommand { + [CmdletBinding(DefaultParameterSetName = 'Parameters')] + param( + [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')] + [string]$Area, + [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')] + [string]$Event, + [Parameter(ParameterSetName = 'Parameters')] + [string]$Data, + [Parameter(ParameterSetName = 'Parameters')] + [hashtable]$Properties, + [Parameter(Mandatory = $true, ParameterSetName = 'Object')] + $Command, + [switch]$AsOutput) + + if ($PSCmdlet.ParameterSetName -eq 'Object') { + Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput + return + } + + $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties + if ($AsOutput) { + $command + } else { + Write-Host $command + } +} + +function Write-LogIssue { + [CmdletBinding()] + param( + [ValidateSet('warning', 'error')] + [Parameter(Mandatory = $true)] + [string]$Type, + [string]$Message, + [string]$ErrCode, + [string]$SourcePath, + [string]$LineNumber, + [string]$ColumnNumber, + [switch]$AsOutput) + + $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{ + 'type' = $Type + 'code' = $ErrCode + 'sourcepath' = $SourcePath + 'linenumber' = $LineNumber + 'columnnumber' = $ColumnNumber + } + if ($AsOutput) { + return $command + } + + if ($Type -eq 'error') { + $foregroundColor = $host.PrivateData.ErrorForegroundColor + $backgroundColor = $host.PrivateData.ErrorBackgroundColor + if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { + $foregroundColor = [System.ConsoleColor]::Red + $backgroundColor = [System.ConsoleColor]::Black + } + } else { + $foregroundColor = $host.PrivateData.WarningForegroundColor + $backgroundColor = $host.PrivateData.WarningBackgroundColor + if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) { + $foregroundColor = [System.ConsoleColor]::Yellow + $backgroundColor = [System.ConsoleColor]::Black + } + } + + Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor +} \ No newline at end of file diff --git a/eng/common/PublishToPackageFeed.proj b/eng/common/PublishToPackageFeed.proj index e17f72644e3e..a1b1333723eb 100644 --- a/eng/common/PublishToPackageFeed.proj +++ b/eng/common/PublishToPackageFeed.proj @@ -53,6 +53,8 @@ https://dotnetfeed.blob.core.windows.net/dotnet-toolset/index.json https://dotnetfeed.blob.core.windows.net/dotnet-windowsdesktop/index.json https://dotnetfeed.blob.core.windows.net/nuget-nugetclient/index.json + https://dotnetfeed.blob.core.windows.net/aspnet-entityframework6/index.json + https://dotnetfeed.blob.core.windows.net/aspnet-blazor/index.json Exist flag) used to consult whether a file exist +# in the repository at a specific commit point. This is populated by inserting +# all files present in the repo at a specific commit point. +$global:RepoFiles = @{} + +$ValidatePackage = { + param( + [string] $PackagePath # Full path to a Symbols.NuGet package + ) + + # Ensure input file exist + if (!(Test-Path $PackagePath)) { + throw "Input file does not exist: $PackagePath" + } + + # Extensions for which we'll look for SourceLink information + # For now we'll only care about Portable & Embedded PDBs + $RelevantExtensions = @(".dll", ".exe", ".pdb") + + Write-Host -NoNewLine "Validating" ([System.IO.Path]::GetFileName($PackagePath)) "... " + + $PackageId = [System.IO.Path]::GetFileNameWithoutExtension($PackagePath) + $ExtractPath = Join-Path -Path $using:ExtractPath -ChildPath $PackageId + $FailedFiles = 0 + + Add-Type -AssemblyName System.IO.Compression.FileSystem + + [System.IO.Directory]::CreateDirectory($ExtractPath); + + $zip = [System.IO.Compression.ZipFile]::OpenRead($PackagePath) + + $zip.Entries | + Where-Object {$RelevantExtensions -contains [System.IO.Path]::GetExtension($_.Name)} | + ForEach-Object { + $FileName = $_.FullName + $Extension = [System.IO.Path]::GetExtension($_.Name) + $FakeName = -Join((New-Guid), $Extension) + $TargetFile = Join-Path -Path $ExtractPath -ChildPath $FakeName + + # We ignore resource DLLs + if ($FileName.EndsWith(".resources.dll")) { + return + } + + [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, $TargetFile, $true) + + $ValidateFile = { + param( + [string] $FullPath, # Full path to the module that has to be checked + [string] $RealPath, + [ref] $FailedFiles + ) + + # Makes easier to reference `sourcelink cli` + Push-Location $using:SourceLinkToolPath + + $SourceLinkInfos = .\sourcelink.exe print-urls $FullPath | Out-String + + if ($LASTEXITCODE -eq 0 -and -not ([string]::IsNullOrEmpty($SourceLinkInfos))) { + $NumFailedLinks = 0 + + # We only care about Http addresses + $Matches = (Select-String '(http[s]?)(:\/\/)([^\s,]+)' -Input $SourceLinkInfos -AllMatches).Matches + + if ($Matches.Count -ne 0) { + $Matches.Value | + ForEach-Object { + $Link = $_ + $CommitUrl = -Join("https://raw.githubusercontent.com/", $using:GHRepoName, "/", $using:GHCommit, "/") + $FilePath = $Link.Replace($CommitUrl, "") + $Status = 200 + $Cache = $using:RepoFiles + + if ( !($Cache.ContainsKey($FilePath)) ) { + try { + $Uri = $Link -as [System.URI] + + # Only GitHub links are valid + if ($Uri.AbsoluteURI -ne $null -and $Uri.Host -match "github") { + $Status = (Invoke-WebRequest -Uri $Link -UseBasicParsing -Method HEAD -TimeoutSec 5).StatusCode + } + else { + $Status = 0 + } + } + catch { + $Status = 0 + } + } + + if ($Status -ne 200) { + if ($NumFailedLinks -eq 0) { + if ($FailedFiles.Value -eq 0) { + Write-Host + } + + Write-Host "`tFile $RealPath has broken links:" + } + + Write-Host "`t`tFailed to retrieve $Link" + + $NumFailedLinks++ + } + } + } + + if ($NumFailedLinks -ne 0) { + $FailedFiles.value++ + $global:LASTEXITCODE = 1 + } + } + + Pop-Location + } + + &$ValidateFile $TargetFile $FileName ([ref]$FailedFiles) + } + + $zip.Dispose() + + if ($FailedFiles -eq 0) { + Write-Host "Passed." + } +} + +function ValidateSourceLinkLinks { + if (!($GHRepoName -Match "^[^\s\/]+/[^\s\/]+$")) { + Write-Host "GHRepoName should be in the format /" + $global:LASTEXITCODE = 1 + return + } + + if (!($GHCommit -Match "^[0-9a-fA-F]{40}$")) { + Write-Host "GHCommit should be a 40 chars hexadecimal string" + $global:LASTEXITCODE = 1 + return + } + + $RepoTreeURL = -Join("https://api.github.com/repos/", $GHRepoName, "/git/trees/", $GHCommit, "?recursive=1") + $CodeExtensions = @(".cs", ".vb", ".fs", ".fsi", ".fsx", ".fsscript") + + try { + # Retrieve the list of files in the repo at that particular commit point and store them in the RepoFiles hash + $Data = Invoke-WebRequest $RepoTreeURL | ConvertFrom-Json | Select-Object -ExpandProperty tree + + foreach ($file in $Data) { + $Extension = [System.IO.Path]::GetExtension($file.path) + + if ($CodeExtensions.Contains($Extension)) { + $RepoFiles[$file.path] = 1 + } + } + } + catch { + Write-Host "Problems downloading the list of files from the repo. Url used: $RepoTreeURL" + $global:LASTEXITCODE = 1 + return + } + + if (Test-Path $ExtractPath) { + Remove-Item $ExtractPath -Force -Recurse -ErrorAction SilentlyContinue + } + + # Process each NuGet package in parallel + $Jobs = @() + Get-ChildItem "$InputPath\*.symbols.nupkg" | + ForEach-Object { + $Jobs += Start-Job -ScriptBlock $ValidatePackage -ArgumentList $_.FullName + } + + foreach ($Job in $Jobs) { + Wait-Job -Id $Job.Id | Receive-Job + } +} + +Measure-Command { ValidateSourceLinkLinks } diff --git a/eng/common/build.ps1 b/eng/common/build.ps1 index d0147db4bd52..4cb2ce489b6c 100644 --- a/eng/common/build.ps1 +++ b/eng/common/build.ps1 @@ -1,6 +1,7 @@ [CmdletBinding(PositionalBinding=$false)] Param( [string][Alias('c')]$configuration = "Debug", + [string]$platform = $null, [string] $projects, [string][Alias('v')]$verbosity = "minimal", [string] $msbuildEngine = $null, @@ -29,6 +30,7 @@ Param( function Print-Usage() { Write-Host "Common settings:" Write-Host " -configuration Build configuration: 'Debug' or 'Release' (short: -c)" + Write-Host " -platform Platform configuration: 'x86', 'x64' or any valid Platform value to pass to msbuild" Write-Host " -verbosity Msbuild verbosity: q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic] (short: -v)" Write-Host " -binaryLog Output binary log (short: -bl)" Write-Host " -help Print help and exit" @@ -77,6 +79,7 @@ function Build { InitializeCustomToolset $bl = if ($binaryLog) { "/bl:" + (Join-Path $LogDir "Build.binlog") } else { "" } + $platformArg = if ($platform) { "/p:Platform=$platform" } else { "" } if ($projects) { # Re-assign properties to a new variable because PowerShell doesn't let us append properties directly for unclear reasons. @@ -88,6 +91,7 @@ function Build { MSBuild $toolsetBuildProj ` $bl ` + $platformArg ` /p:Configuration=$configuration ` /p:RepoRoot=$RepoRoot ` /p:Restore=$restore ` @@ -122,12 +126,15 @@ try { . $configureToolsetScript } + if (($restore) -and ($null -eq $env:DisableNativeToolsetInstalls)) { + InitializeNativeTools + } + Build } catch { - Write-Host $_ - Write-Host $_.Exception Write-Host $_.ScriptStackTrace + Write-PipelineTaskError -Message $_ ExitWithExitCode 1 } diff --git a/eng/common/build.sh b/eng/common/build.sh index 40b1e8ec73e3..6236fc4d38cd 100755 --- a/eng/common/build.sh +++ b/eng/common/build.sh @@ -35,7 +35,7 @@ usage() echo " --nodeReuse Sets nodereuse msbuild parameter ('true' or 'false')" echo " --warnAsError Sets warnaserror msbuild parameter ('true' or 'false')" echo "" - echo "Command line arguments starting with '/p:' are passed through to MSBuild." + echo "Command line arguments not listed above are passed thru to msbuild." echo "Arguments can also be passed in with a single hyphen." } @@ -66,6 +66,7 @@ ci=false warn_as_error=true node_reuse=true binary_log=false +pipelines_log=false projects='' configuration='Debug' @@ -92,6 +93,9 @@ while [[ $# > 0 ]]; do -binarylog|-bl) binary_log=true ;; + -pipelineslog|-pl) + pipelines_log=true + ;; -restore|-r) restore=true ;; @@ -137,22 +141,8 @@ while [[ $# > 0 ]]; do node_reuse=$2 shift ;; - -p:*|/p:*) - properties="$properties $1" - ;; - -m:*|/m:*) - properties="$properties $1" - ;; - -bl:*|/bl:*) - properties="$properties $1" - ;; - -dl:*|/dl:*) - properties="$properties $1" - ;; *) - echo "Invalid argument: $1" - usage - exit 1 + properties="$properties $1" ;; esac @@ -160,6 +150,7 @@ while [[ $# > 0 ]]; do done if [[ "$ci" == true ]]; then + pipelines_log=true binary_log=true node_reuse=false fi @@ -218,4 +209,8 @@ if [[ -n "${useInstalledDotNetCli:-}" ]]; then use_installed_dotnet_cli="$useInstalledDotNetCli" fi +if [[ "$restore" == true && -z ${DisableNativeToolsetInstalls:-} ]]; then + InitializeNativeTools +fi + Build diff --git a/eng/common/cross/arm/sources.list.vivid b/eng/common/cross/arm/sources.list.vivid deleted file mode 100644 index 0b1215e475ac..000000000000 --- a/eng/common/cross/arm/sources.list.vivid +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ vivid main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ vivid main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ vivid-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ vivid-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ vivid-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ vivid-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ vivid-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ vivid-security main restricted universe multiverse \ No newline at end of file diff --git a/eng/common/cross/arm/sources.list.wily b/eng/common/cross/arm/sources.list.wily deleted file mode 100644 index e23d1e02a05d..000000000000 --- a/eng/common/cross/arm/sources.list.wily +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ wily main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ wily main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ wily-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ wily-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ wily-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ wily-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ wily-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ wily-security main restricted universe multiverse \ No newline at end of file diff --git a/eng/common/cross/arm64/sources.list.buster b/eng/common/cross/arm64/sources.list.buster new file mode 100644 index 000000000000..7194ac64a960 --- /dev/null +++ b/eng/common/cross/arm64/sources.list.buster @@ -0,0 +1,11 @@ +deb http://deb.debian.org/debian buster main +deb-src http://deb.debian.org/debian buster main + +deb http://deb.debian.org/debian-security/ buster/updates main +deb-src http://deb.debian.org/debian-security/ buster/updates main + +deb http://deb.debian.org/debian buster-updates main +deb-src http://deb.debian.org/debian buster-updates main + +deb http://deb.debian.org/debian buster-backports main contrib non-free +deb-src http://deb.debian.org/debian buster-backports main contrib non-free diff --git a/eng/common/cross/arm64/sources.list.stretch b/eng/common/cross/arm64/sources.list.stretch new file mode 100644 index 000000000000..0e1215774368 --- /dev/null +++ b/eng/common/cross/arm64/sources.list.stretch @@ -0,0 +1,12 @@ +deb http://deb.debian.org/debian stretch main +deb-src http://deb.debian.org/debian stretch main + +deb http://deb.debian.org/debian-security/ stretch/updates main +deb-src http://deb.debian.org/debian-security/ stretch/updates main + +deb http://deb.debian.org/debian stretch-updates main +deb-src http://deb.debian.org/debian stretch-updates main + +deb http://deb.debian.org/debian stretch-backports main contrib non-free +deb-src http://deb.debian.org/debian stretch-backports main contrib non-free + diff --git a/eng/common/cross/arm64/sources.list.vivid b/eng/common/cross/arm64/sources.list.vivid deleted file mode 100644 index 0b1215e475ac..000000000000 --- a/eng/common/cross/arm64/sources.list.vivid +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ vivid main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ vivid main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ vivid-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ vivid-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ vivid-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ vivid-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ vivid-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ vivid-security main restricted universe multiverse \ No newline at end of file diff --git a/eng/common/cross/arm64/sources.list.wily b/eng/common/cross/arm64/sources.list.wily deleted file mode 100644 index e23d1e02a05d..000000000000 --- a/eng/common/cross/arm64/sources.list.wily +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ wily main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ wily main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ wily-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ wily-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ wily-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ wily-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ wily-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ wily-security main restricted universe multiverse \ No newline at end of file diff --git a/eng/common/cross/build-rootfs.sh b/eng/common/cross/build-rootfs.sh index 805948ca83c7..34d3d2ba1fe1 100644 --- a/eng/common/cross/build-rootfs.sh +++ b/eng/common/cross/build-rootfs.sh @@ -2,21 +2,21 @@ usage() { - echo "Usage: $0 [BuildArch] [LinuxCodeName] [lldbx.y] [--skipunmount]" + echo "Usage: $0 [BuildArch] [LinuxCodeName] [lldbx.y] [--skipunmount] --rootfsdir ]" echo "BuildArch can be: arm(default), armel, arm64, x86" - echo "LinuxCodeName - optional, Code name for Linux, can be: trusty(default), vivid, wily, xenial, zesty, bionic, alpine. If BuildArch is armel, LinuxCodeName is jessie(default) or tizen." - echo "lldbx.y - optional, LLDB version, can be: lldb3.6(default), lldb3.8, lldb3.9, lldb4.0, no-lldb. Ignored for alpine" + echo "LinuxCodeName - optional, Code name for Linux, can be: trusty, xenial(default), zesty, bionic, alpine. If BuildArch is armel, LinuxCodeName is jessie(default) or tizen." + echo "lldbx.y - optional, LLDB version, can be: lldb3.9(default), lldb4.0, lldb5.0, lldb6.0 no-lldb. Ignored for alpine" echo "--skipunmount - optional, will skip the unmount of rootfs folder." exit 1 } -__LinuxCodeName=trusty +__LinuxCodeName=xenial __CrossDir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) __InitialDir=$PWD __BuildArch=arm __UbuntuArch=armhf __UbuntuRepo="http://ports.ubuntu.com/" -__LLDB_Package="lldb-3.6-dev" +__LLDB_Package="liblldb-3.9-dev" __SkipUnmount=0 # base development support @@ -53,8 +53,12 @@ __AlpinePackages+=" openssl-dev" __AlpinePackages+=" zlib-dev" __UnprocessedBuildArgs= -for i in "$@" ; do - lowerI="$(echo $i | awk '{print tolower($0)}')" +while :; do + if [ $# -le 0 ]; then + break + fi + + lowerI="$(echo $1 | awk '{print tolower($0)}')" case $lowerI in -?|-h|--help) usage @@ -95,38 +99,49 @@ for i in "$@" ; do lldb4.0) __LLDB_Package="liblldb-4.0-dev" ;; + lldb5.0) + __LLDB_Package="liblldb-5.0-dev" + ;; + lldb6.0) + __LLDB_Package="liblldb-6.0-dev" + ;; no-lldb) unset __LLDB_Package ;; - vivid) + trusty) # Ubuntu 14.04 if [ "$__LinuxCodeName" != "jessie" ]; then - __LinuxCodeName=vivid + __LinuxCodeName=trusty fi ;; - wily) - if [ "$__LinuxCodeName" != "jessie" ]; then - __LinuxCodeName=wily - fi - ;; - xenial) + xenial) # Ubuntu 16.04 if [ "$__LinuxCodeName" != "jessie" ]; then __LinuxCodeName=xenial fi ;; - zesty) + zesty) # Ubuntu 17.04 if [ "$__LinuxCodeName" != "jessie" ]; then __LinuxCodeName=zesty fi ;; - bionic) + bionic) # Ubuntu 18.04 if [ "$__LinuxCodeName" != "jessie" ]; then __LinuxCodeName=bionic fi ;; - jessie) + jessie) # Debian 8 __LinuxCodeName=jessie __UbuntuRepo="http://ftp.debian.org/debian/" ;; + stretch) # Debian 9 + __LinuxCodeName=stretch + __UbuntuRepo="http://ftp.debian.org/debian/" + __LLDB_Package="liblldb-6.0-dev" + ;; + buster) # Debian 10 + __LinuxCodeName=buster + __UbuntuRepo="http://ftp.debian.org/debian/" + __LLDB_Package="liblldb-6.0-dev" + ;; tizen) if [ "$__BuildArch" != "armel" ]; then echo "Tizen is available only for armel." @@ -144,10 +159,16 @@ for i in "$@" ; do --skipunmount) __SkipUnmount=1 ;; + --rootfsdir|-rootfsdir) + shift + __RootfsDir=$1 + ;; *) - __UnprocessedBuildArgs="$__UnprocessedBuildArgs $i" + __UnprocessedBuildArgs="$__UnprocessedBuildArgs $1" ;; esac + + shift done if [ "$__BuildArch" == "armel" ]; then @@ -155,12 +176,14 @@ if [ "$__BuildArch" == "armel" ]; then fi __UbuntuPackages+=" ${__LLDB_Package:-}" -__RootfsDir="$__CrossDir/rootfs/$__BuildArch" - -if [[ -n "$ROOTFS_DIR" ]]; then +if [ -z "$__RootfsDir" ] && [ ! -z "$ROOTFS_DIR" ]; then __RootfsDir=$ROOTFS_DIR fi +if [ -z "$__RootfsDir" ]; then + __RootfsDir="$__CrossDir/rootfs/$__BuildArch" +fi + if [ -d "$__RootfsDir" ]; then if [ $__SkipUnmount == 0 ]; then umount $__RootfsDir/* diff --git a/eng/common/cross/x86/sources.list.vivid b/eng/common/cross/x86/sources.list.vivid deleted file mode 100644 index 26d37b20fc37..000000000000 --- a/eng/common/cross/x86/sources.list.vivid +++ /dev/null @@ -1,11 +0,0 @@ -deb http://archive.ubuntu.com/ubuntu/ vivid main restricted universe -deb-src http://archive.ubuntu.com/ubuntu/ vivid main restricted universe - -deb http://archive.ubuntu.com/ubuntu/ vivid-updates main restricted universe -deb-src http://archive.ubuntu.com/ubuntu/ vivid-updates main restricted universe - -deb http://archive.ubuntu.com/ubuntu/ vivid-backports main restricted -deb-src http://archive.ubuntu.com/ubuntu/ vivid-backports main restricted - -deb http://archive.ubuntu.com/ubuntu/ vivid-security main restricted universe multiverse -deb-src http://archive.ubuntu.com/ubuntu/ vivid-security main restricted universe multiverse diff --git a/eng/common/cross/x86/sources.list.wily b/eng/common/cross/x86/sources.list.wily deleted file mode 100644 index c4b0b442ab6b..000000000000 --- a/eng/common/cross/x86/sources.list.wily +++ /dev/null @@ -1,11 +0,0 @@ -deb http://archive.ubuntu.com/ubuntu/ wily main restricted universe -deb-src http://archive.ubuntu.com/ubuntu/ wily main restricted universe - -deb http://archive.ubuntu.com/ubuntu/ wily-updates main restricted universe -deb-src http://archive.ubuntu.com/ubuntu/ wily-updates main restricted universe - -deb http://archive.ubuntu.com/ubuntu/ wily-backports main restricted -deb-src http://archive.ubuntu.com/ubuntu/ wily-backports main restricted - -deb http://archive.ubuntu.com/ubuntu/ wily-security main restricted universe multiverse -deb-src http://archive.ubuntu.com/ubuntu/ wily-security main restricted universe multiverse diff --git a/eng/common/darc-init.ps1 b/eng/common/darc-init.ps1 index 81ffd16779cb..dea7cdd903b1 100644 --- a/eng/common/darc-init.ps1 +++ b/eng/common/darc-init.ps1 @@ -1,5 +1,6 @@ param ( - $darcVersion = $null + $darcVersion = $null, + $versionEndpoint = "https://maestro-prod.westus2.cloudapp.azure.com/api/assets/darc-version?api-version=2019-01-16" ) $verbosity = "m" @@ -16,13 +17,13 @@ function InstallDarcCli ($darcVersion) { Invoke-Expression "& `"$dotnet`" tool uninstall $darcCliPackageName -g" } - # Until we can anonymously query the BAR API for the latest arcade-services - # build applied to the PROD channel, this is hardcoded. + # If the user didn't explicitly specify the darc version, + # query the Maestro API for the correct version of darc to install. if (-not $darcVersion) { - $darcVersion = '1.1.0-beta.19205.4' + $darcVersion = $(Invoke-WebRequest -Uri $versionEndpoint -UseBasicParsing).Content } - $arcadeServicesSource = 'https://dotnetfeed.blob.core.windows.net/dotnet-arcade/index.json' + $arcadeServicesSource = 'https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json' Write-Host "Installing Darc CLI version $darcVersion..." Write-Host "You may need to restart your command window if this is the first dotnet tool you have installed." diff --git a/eng/common/darc-init.sh b/eng/common/darc-init.sh index bd7eb4639864..abdd0bc05a13 100755 --- a/eng/common/darc-init.sh +++ b/eng/common/darc-init.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash source="${BASH_SOURCE[0]}" -darcVersion="1.1.0-beta.19205.4" +darcVersion='' +versionEndpoint="https://maestro-prod.westus2.cloudapp.azure.com/api/assets/darc-version?api-version=2019-01-16" while [[ $# > 0 ]]; do opt="$(echo "$1" | awk '{print tolower($0)}')" @@ -10,6 +11,10 @@ while [[ $# > 0 ]]; do darcVersion=$2 shift ;; + --versionendpoint) + versionEndpoint=$2 + shift + ;; *) echo "Invalid argument: $1" usage @@ -33,6 +38,10 @@ verbosity=m . "$scriptroot/tools.sh" +if [ -z "$darcVersion" ]; then + darcVersion=$(curl -X GET "$versionEndpoint" -H "accept: text/plain") +fi + function InstallDarcCli { local darc_cli_package_name="microsoft.dotnet.darc" @@ -45,9 +54,9 @@ function InstallDarcCli { echo $($dotnet_root/dotnet tool uninstall $darc_cli_package_name -g) fi - local arcadeServicesSource="https://dotnetfeed.blob.core.windows.net/dotnet-arcade/index.json" + local arcadeServicesSource="https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json" - echo "Installing Darc CLI version $toolset_version..." + echo "Installing Darc CLI version $darcVersion..." echo "You may need to restart your command shell if this is the first dotnet tool you have installed." echo $($dotnet_root/dotnet tool install $darc_cli_package_name --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity -g) } diff --git a/eng/common/dotnet-install.cmd b/eng/common/dotnet-install.cmd new file mode 100644 index 000000000000..b1c2642e76f7 --- /dev/null +++ b/eng/common/dotnet-install.cmd @@ -0,0 +1,2 @@ +@echo off +powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0dotnet-install.ps1""" %*" \ No newline at end of file diff --git a/eng/common/dotnet-install.ps1 b/eng/common/dotnet-install.ps1 new file mode 100644 index 000000000000..0b629b8301a1 --- /dev/null +++ b/eng/common/dotnet-install.ps1 @@ -0,0 +1,27 @@ +[CmdletBinding(PositionalBinding=$false)] +Param( + [string] $verbosity = "minimal", + [string] $architecture = "", + [string] $version = "Latest", + [string] $runtime = "dotnet" +) + +. $PSScriptRoot\tools.ps1 + +$dotnetRoot = Join-Path $RepoRoot ".dotnet" + +$installdir = $dotnetRoot +try { + if ($architecture -and $architecture.Trim() -eq "x86") { + $installdir = Join-Path $installdir "x86" + } + InstallDotNet $installdir $version $architecture $runtime $true +} +catch { + Write-Host $_ + Write-Host $_.Exception + Write-Host $_.ScriptStackTrace + ExitWithExitCode 1 +} + +ExitWithExitCode 0 diff --git a/eng/common/dotnet-install.sh b/eng/common/dotnet-install.sh new file mode 100644 index 000000000000..c3072c958af0 --- /dev/null +++ b/eng/common/dotnet-install.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash + +source="${BASH_SOURCE[0]}" +# resolve $source until the file is no longer a symlink +while [[ -h "$source" ]]; do + scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + source="$(readlink "$source")" + # if $source was a relative symlink, we need to resolve it relative to the path where the + # symlink file was located + [[ $source != /* ]] && source="$scriptroot/$source" +done +scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + +version='Latest' +architecture='' +runtime='dotnet' +while [[ $# > 0 ]]; do + opt="$(echo "$1" | awk '{print tolower($0)}')" + case "$opt" in + -version|-v) + shift + version="$1" + ;; + -architecture|-a) + shift + architecture="$1" + ;; + -runtime|-r) + shift + runtime="$1" + ;; + *) + echo "Invalid argument: $1" + usage + exit 1 + ;; + esac + shift +done + +. "$scriptroot/tools.sh" +dotnetRoot="$repo_root/.dotnet" +InstallDotNet $dotnetRoot $version "$architecture" $runtime true || { + local exit_code=$? + echo "dotnet-install.sh failed (exit code '$exit_code')." >&2 + ExitWithExitCode $exit_code +} + +ExitWithExitCode 0 diff --git a/eng/common/init-tools-native.ps1 b/eng/common/init-tools-native.ps1 index 495a563a7583..a4306bd37e14 100644 --- a/eng/common/init-tools-native.ps1 +++ b/eng/common/init-tools-native.ps1 @@ -41,9 +41,13 @@ Param ( [switch] $Force = $False, [int] $DownloadRetries = 5, [int] $RetryWaitTimeInSeconds = 30, - [string] $GlobalJsonFile = "$PSScriptRoot\..\..\global.json" + [string] $GlobalJsonFile ) +if (!$GlobalJsonFile) { + $GlobalJsonFile = Join-Path (Get-Item $PSScriptRoot).Parent.Parent.FullName "global.json" +} + Set-StrictMode -version 2.0 $ErrorActionPreference="Stop" diff --git a/eng/common/init-tools-native.sh b/eng/common/init-tools-native.sh index 54b70f678ba3..fc72d13948e8 100644 --- a/eng/common/init-tools-native.sh +++ b/eng/common/init-tools-native.sh @@ -9,7 +9,7 @@ clean=false force=false download_retries=5 retry_wait_time_seconds=30 -global_json_file="${scriptroot}/../../global.json" +global_json_file="$(dirname "$(dirname "${scriptroot}")")/global.json" declare -A native_assets . $scriptroot/native/common-library.sh @@ -71,6 +71,7 @@ function ReadGlobalJsonNativeTools { local native_tools_list=$(echo $native_tools_section | awk -F"[{}]" '{print $2}') native_tools_list=${native_tools_list//[\" ]/} native_tools_list=${native_tools_list//,/$'\n'} + native_tools_list="$(echo -e "${native_tools_list}" | tr -d '[:space:]')" local old_IFS=$IFS while read -r line; do @@ -116,8 +117,6 @@ else installer_command+=" --clean" fi - echo "Installing $tool version $tool_version" - echo "Executing '$installer_command'" $installer_command if [[ $? != 0 ]]; then @@ -127,19 +126,16 @@ else done fi -if [[ ! -z $clean ]]; then +if [[ $clean = true ]]; then exit 0 fi if [[ -d $install_bin ]]; then echo "Native tools are available from $install_bin" - if [[ !-z BUILD_BUILDNUMBER ]]; then - echo "##vso[task.prependpath]$install_bin" - fi + echo "##vso[task.prependpath]$install_bin" else echo "Native tools install directory does not exist, installation failed" >&2 exit 1 fi exit 0 - diff --git a/eng/common/templates/job/job.yml b/eng/common/templates/job/job.yml index 74dd81fdc0a3..1814e0ab6124 100644 --- a/eng/common/templates/job/job.yml +++ b/eng/common/templates/job/job.yml @@ -43,9 +43,12 @@ parameters: # Optional: enable sending telemetry enableTelemetry: false - # Optional: define the helix repo for telemeetry (example: 'dotnet/arcade') + # Optional: define the helix repo for telemetry (example: 'dotnet/arcade') helixRepo: '' + # Optional: define the helix type for telemetry (example: 'build/product/') + helixType: '' + # Required: name of the job name: '' @@ -87,6 +90,9 @@ jobs: timeoutInMinutes: ${{ parameters.timeoutInMinutes }} variables: + - ${{ if eq(parameters.enableTelemetry, 'true') }}: + - name: DOTNET_CLI_TELEMETRY_PROFILE + value: '$(Build.Repository.Uri)' - ${{ each variable in parameters.variables }}: # handle name-value variable syntax # example: @@ -122,6 +128,8 @@ jobs: displayName: 'Send Helix Start Telemetry' inputs: helixRepo: ${{ parameters.helixRepo }} + ${{ if ne(parameters.helixType, '') }}: + helixType: ${{ parameters.helixType }} buildConfig: $(_BuildConfig) runAsPublic: ${{ parameters.runAsPublic }} continueOnError: ${{ parameters.continueOnError }} diff --git a/eng/common/templates/steps/helix-publish.yml b/eng/common/templates/steps/helix-publish.yml deleted file mode 100644 index 470ab65da0c6..000000000000 --- a/eng/common/templates/steps/helix-publish.yml +++ /dev/null @@ -1,51 +0,0 @@ -parameters: - HelixSource: 'pr/dotnet-github-anon-kaonashi-bot' - HelixType: ̓'tests/default' - HelixBuild: $(Build.BuildNumber) - HelixTargetQueues: '' - HelixAccessToken: '' - HelixPreCommands: '' - HelixPostCommands: '' - WorkItemDirectory: '' - WorkItemCommand: '' - CorrelationPayloadDirectory: '' - XUnitProjects: '' - XUnitTargetFramework: '' - XUnitRunnerVersion: '' - IncludeDotNetCli: false - DotNetCliPackageType: '' - DotNetCliVersion: '' - EnableXUnitReporter: false - WaitForWorkItemCompletion: true - condition: succeeded() - continueOnError: false - -steps: - - task: DotNetCoreCLI@2 - inputs: - command: custom - projects: eng/common/helixpublish.proj - custom: msbuild - arguments: '/bl:$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/SendToHelix.binlog' - displayName: Send job to Helix - env: - HelixSource: ${{ parameters.HelixSource }} - HelixType: ${{ parameters.HelixType }} - HelixBuild: ${{ parameters.HelixBuild }} - HelixTargetQueues: ${{ parameters.HelixTargetQueues }} - HelixAccessToken: ${{ parameters.HelixAccessToken }} - HelixPreCommands: ${{ parameters.HelixPreCommands }} - HelixPostCommands: ${{ parameters.HelixPostCommands }} - WorkItemDirectory: ${{ parameters.WorkItemDirectory }} - WorkItemCommand: ${{ parameters.WorkItemCommand }} - CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} - XUnitProjects: ${{ parameters.XUnitProjects }} - XUnitRuntimeTargetFramework: ${{ parameters.XUnitTargetFramework }} - XUnitRunnerVersion: ${{ parameters.XUnitRunnerVersion }} - IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} - DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} - DotNetCliVersion: ${{ parameters.DotNetCliVersion }} - EnableXUnitReporter: ${{ parameters.EnableXUnitReporter }} - WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} - condition: ${{ parameters.condition }} - continueOnError: ${{ parameters.continueOnError }} diff --git a/eng/common/templates/steps/send-to-helix.yml b/eng/common/templates/steps/send-to-helix.yml index 7c185e94147a..05df886f55f7 100644 --- a/eng/common/templates/steps/send-to-helix.yml +++ b/eng/common/templates/steps/send-to-helix.yml @@ -5,6 +5,7 @@ parameters: HelixBuild: $(Build.BuildNumber) # required -- the build number Helix will use to identify this -- automatically set to the AzDO build number HelixTargetQueues: '' # required -- semicolon delimited list of Helix queues to test on; see https://helix.dot.net/ for a list of queues HelixAccessToken: '' # required -- access token to make Helix API requests; should be provided by the appropriate variable group + HelixConfiguration: '' # optional -- additional property attached to a job HelixPreCommands: '' # optional -- commands to run before Helix work item execution HelixPostCommands: '' # optional -- commands to run after Helix work item execution WorkItemDirectory: '' # optional -- a payload directory to zip up and send to Helix; requires WorkItemCommand; incompatible with XUnitProjects @@ -23,7 +24,7 @@ parameters: WaitForWorkItemCompletion: true # optional -- true will make the task wait until work items have been completed and fail the build if work items fail. False is "fire and forget." IsExternal: false # [DEPRECATED] -- doesn't do anything, jobs are external if HelixAccessToken is empty and Creator is set Creator: '' # optional -- if the build is external, use this to specify who is sending the job - DisplayNamePrefix: 'Send job to Helix' # optional -- rename the beginning of the displayName of the steps in AzDO + DisplayNamePrefix: 'Run Tests' # optional -- rename the beginning of the displayName of the steps in AzDO condition: succeeded() # optional -- condition for step to execute; defaults to succeeded() continueOnError: false # optional -- determines whether to continue the build if the step errors; defaults to false @@ -35,6 +36,7 @@ steps: HelixSource: ${{ parameters.HelixSource }} HelixType: ${{ parameters.HelixType }} HelixBuild: ${{ parameters.HelixBuild }} + HelixConfiguration: ${{ parameters.HelixConfiguration }} HelixTargetQueues: ${{ parameters.HelixTargetQueues }} HelixAccessToken: ${{ parameters.HelixAccessToken }} HelixPreCommands: ${{ parameters.HelixPreCommands }} @@ -64,6 +66,7 @@ steps: HelixSource: ${{ parameters.HelixSource }} HelixType: ${{ parameters.HelixType }} HelixBuild: ${{ parameters.HelixBuild }} + HelixConfiguration: ${{ parameters.HelixConfiguration }} HelixTargetQueues: ${{ parameters.HelixTargetQueues }} HelixAccessToken: ${{ parameters.HelixAccessToken }} HelixPreCommands: ${{ parameters.HelixPreCommands }} diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index 5c4a129c8632..3983d719be3f 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -11,6 +11,12 @@ # Binary log must be enabled on CI. [bool]$binaryLog = if (Test-Path variable:binaryLog) { $binaryLog } else { $ci } +# Set to true to use the pipelines logger which will enable Azure logging output. +# https://github.com/Microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md +# This flag is meant as a temporary opt-opt for the feature while validate it across +# our consumers. It will be deleted in the future. +[bool]$pipelinesLog = if (Test-Path variable:pipelinesLog) { $pipelinesLog } else { $ci } + # Turns on machine preparation/clean up code that changes the machine state (e.g. kills build processes). [bool]$prepareMachine = if (Test-Path variable:prepareMachine) { $prepareMachine } else { $false } @@ -86,6 +92,68 @@ function Exec-Process([string]$command, [string]$commandArgs) { } } +function Write-PipelineTaskError { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Message, + [Parameter(Mandatory = $false)] + [string]$Type = 'error', + [string]$ErrCode, + [string]$SourcePath, + [string]$LineNumber, + [string]$ColumnNumber, + [switch]$AsOutput) + + if(!$ci) { + if($Type -eq 'error') { + Write-Error $Message + return + } + elseif ($Type -eq 'warning') { + Write-Warning $Message + return + } + } + + if(($Type -ne 'error') -and ($Type -ne 'warning')) { + Write-Host $Message + return + } + if(-not $PSBoundParameters.ContainsKey('Type')) { + $PSBoundParameters.Add('Type', 'error') + } + Write-LogIssue @PSBoundParameters +} + +function Write-PipelineSetVariable { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [string]$Name, + [string]$Value, + [switch]$Secret, + [switch]$AsOutput) + + if($ci) { + Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{ + 'variable' = $Name + 'issecret' = $Secret + } -AsOutput:$AsOutput + } +} + +function Write-PipelinePrependPath { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + [string]$Path, + [switch]$AsOutput) + if($ci) { + Write-LoggingCommand -Area 'task' -Event 'prependpath' -Data $Path -AsOutput:$AsOutput + } +} + function InitializeDotNetCli([bool]$install) { if (Test-Path variable:global:_DotNetInstallDir) { return $global:_DotNetInstallDir @@ -108,7 +176,7 @@ function InitializeDotNetCli([bool]$install) { } # Find the first path on %PATH% that contains the dotnet.exe - if ($useInstalledDotNetCli -and ($env:DOTNET_INSTALL_DIR -eq $null)) { + if ($useInstalledDotNetCli -and (-not $globalJsonHasRuntimes) -and ($env:DOTNET_INSTALL_DIR -eq $null)) { $dotnetCmd = Get-Command "dotnet.exe" -ErrorAction SilentlyContinue if ($dotnetCmd -ne $null) { $env:DOTNET_INSTALL_DIR = Split-Path $dotnetCmd.Path -Parent @@ -119,7 +187,7 @@ function InitializeDotNetCli([bool]$install) { # Use dotnet installation specified in DOTNET_INSTALL_DIR if it contains the required SDK version, # otherwise install the dotnet CLI and SDK to repo local .dotnet directory to avoid potential permission issues. - if (($env:DOTNET_INSTALL_DIR -ne $null) -and (Test-Path(Join-Path $env:DOTNET_INSTALL_DIR "sdk\$dotnetSdkVersion"))) { + if ((-not $globalJsonHasRuntimes) -and ($env:DOTNET_INSTALL_DIR -ne $null) -and (Test-Path(Join-Path $env:DOTNET_INSTALL_DIR "sdk\$dotnetSdkVersion"))) { $dotnetRoot = $env:DOTNET_INSTALL_DIR } else { $dotnetRoot = Join-Path $RepoRoot ".dotnet" @@ -128,7 +196,7 @@ function InitializeDotNetCli([bool]$install) { if ($install) { InstallDotNetSdk $dotnetRoot $dotnetSdkVersion } else { - Write-Host "Unable to find dotnet with SDK version '$dotnetSdkVersion'" -ForegroundColor Red + Write-PipelineTaskError "Unable to find dotnet with SDK version '$dotnetSdkVersion'" ExitWithExitCode 1 } } @@ -141,18 +209,16 @@ function InitializeDotNetCli([bool]$install) { # It also ensures that VS msbuild will use the downloaded sdk targets. $env:PATH = "$dotnetRoot;$env:PATH" - if ($ci) { - # Make Sure that our bootstrapped dotnet cli is avaliable in future steps of the Azure Pipelines build - Write-Host "##vso[task.prependpath]$dotnetRoot" - Write-Host "##vso[task.setvariable variable=DOTNET_MULTILEVEL_LOOKUP]0" - Write-Host "##vso[task.setvariable variable=DOTNET_SKIP_FIRST_TIME_EXPERIENCE]1" - } + # Make Sure that our bootstrapped dotnet cli is avaliable in future steps of the Azure Pipelines build + Write-PipelinePrependPath -Path $dotnetRoot + Write-PipelineSetVariable -Name 'DOTNET_MULTILEVEL_LOOKUP' -Value '0' + Write-PipelineSetVariable -Name 'DOTNET_SKIP_FIRST_TIME_EXPERIENCE' -Value '1' return $global:_DotNetInstallDir = $dotnetRoot } function GetDotNetInstallScript([string] $dotnetRoot) { - $installScript = "$dotnetRoot\dotnet-install.ps1" + $installScript = Join-Path $dotnetRoot "dotnet-install.ps1" if (!(Test-Path $installScript)) { Create-Directory $dotnetRoot Invoke-WebRequest "https://dot.net/v1/dotnet-install.ps1" -OutFile $installScript @@ -162,11 +228,23 @@ function GetDotNetInstallScript([string] $dotnetRoot) { } function InstallDotNetSdk([string] $dotnetRoot, [string] $version, [string] $architecture = "") { + InstallDotNet $dotnetRoot $version $architecture +} + +function InstallDotNet([string] $dotnetRoot, [string] $version, [string] $architecture = "", [string] $runtime = "", [bool] $skipNonVersionedFiles = $false) { $installScript = GetDotNetInstallScript $dotnetRoot $installScript = GetDotNetInstallScript $dotnetRoot - $archArg = if ($architecture) { $architecture } else { "" } - & $installScript -Version $version -InstallDir $dotnetRoot -Architecture $archArg + $installParameters = @{ + Version = $version + InstallDir = $dotnetRoot + } + + if ($architecture) { $installParameters.Architecture = $architecture } + if ($runtime) { $installParameters.Runtime = $runtime } + if ($skipNonVersionedFiles) { $installParameters.SkipNonVersionedFiles = $skipNonVersionedFiles } + + & $installScript @installParameters if ($lastExitCode -ne 0) { - Write-Host "Failed to install dotnet cli (exit code '$lastExitCode')." -ForegroundColor Red + Write-PipelineTaskError -Message "Failed to install dotnet cli (exit code '$lastExitCode')." ExitWithExitCode $lastExitCode } } @@ -195,7 +273,11 @@ function InitializeVisualStudioMSBuild([bool]$install, [object]$vsRequirements = if ($env:VSINSTALLDIR -ne $null) { $msbuildCmd = Get-Command "msbuild.exe" -ErrorAction SilentlyContinue if ($msbuildCmd -ne $null) { - if ($msbuildCmd.Version -ge $vsMinVersion) { + # Workaround for https://github.com/dotnet/roslyn/issues/35793 + # Due to this issue $msbuildCmd.Version returns 0.0.0.0 for msbuild.exe 16.2+ + $msbuildVersion = [Version]::new((Get-Item $msbuildCmd.Path).VersionInfo.ProductVersion.Split(@('-', '+'))[0]) + + if ($msbuildVersion -ge $vsMinVersion) { return $global:_MSBuildExe = $msbuildCmd.Path } @@ -336,22 +418,22 @@ function InitializeBuildTool() { if ($msbuildEngine -eq "dotnet") { if (!$dotnetRoot) { - Write-Host "/global.json must specify 'tools.dotnet'." -ForegroundColor Red + Write-PipelineTaskError "/global.json must specify 'tools.dotnet'." ExitWithExitCode 1 } - $buildTool = @{ Path = Join-Path $dotnetRoot "dotnet.exe"; Command = "msbuild" } + $buildTool = @{ Path = Join-Path $dotnetRoot "dotnet.exe"; Command = "msbuild"; Tool = "dotnet"; Framework = "netcoreapp2.1" } } elseif ($msbuildEngine -eq "vs") { try { $msbuildPath = InitializeVisualStudioMSBuild -install:$restore } catch { - Write-Host $_ -ForegroundColor Red + Write-PipelineTaskError $_ ExitWithExitCode 1 } - $buildTool = @{ Path = $msbuildPath; Command = "" } + $buildTool = @{ Path = $msbuildPath; Command = ""; Tool = "vs"; Framework = "net472" } } else { - Write-Host "Unexpected value of -msbuildEngine: '$msbuildEngine'." -ForegroundColor Red + Write-PipelineTaskError "Unexpected value of -msbuildEngine: '$msbuildEngine'." ExitWithExitCode 1 } @@ -368,7 +450,7 @@ function GetDefaultMSBuildEngine() { return "dotnet" } - Write-Host "-msbuildEngine must be specified, or /global.json must specify 'tools.dotnet' or 'tools.vs'." -ForegroundColor Red + Write-PipelineTaskError "-msbuildEngine must be specified, or /global.json must specify 'tools.dotnet' or 'tools.vs'." ExitWithExitCode 1 } @@ -391,6 +473,16 @@ function GetSdkTaskProject([string]$taskName) { return Join-Path (Split-Path (InitializeToolset) -Parent) "SdkTasks\$taskName.proj" } +function InitializeNativeTools() { + if (Get-Member -InputObject $GlobalJson -Name "native-tools") { + $nativeArgs="" + if ($ci) { + $nativeArgs = "-InstallDirectory $ToolsDir" + } + Invoke-Expression "& `"$PSScriptRoot/init-tools-native.ps1`" $nativeArgs" + } +} + function InitializeToolset() { if (Test-Path variable:global:_ToolsetBuildProj) { return $global:_ToolsetBuildProj @@ -409,7 +501,7 @@ function InitializeToolset() { } if (-not $restore) { - Write-Host "Toolset version $toolsetVersion has not been restored." -ForegroundColor Red + Write-PipelineTaskError "Toolset version $toolsetVersion has not been restored." ExitWithExitCode 1 } @@ -419,7 +511,8 @@ function InitializeToolset() { $bl = if ($binaryLog) { "/bl:" + (Join-Path $LogDir "ToolsetRestore.binlog") } else { "" } '' | Set-Content $proj - MSBuild $proj $bl /t:__WriteToolsetLocation /clp:ErrorsOnly`;NoSummary /p:__ToolsetLocationOutputFile=$toolsetLocationFile + + MSBuild-Core $proj $bl /t:__WriteToolsetLocation /clp:ErrorsOnly`;NoSummary /p:__ToolsetLocationOutputFile=$toolsetLocationFile $path = Get-Content $toolsetLocationFile -TotalCount 1 if (!(Test-Path $path)) { @@ -449,6 +542,23 @@ function Stop-Processes() { # Terminates the script if the build fails. # function MSBuild() { + if ($pipelinesLog) { + $buildTool = InitializeBuildTool + $toolsetBuildProject = InitializeToolset + $path = Split-Path -parent $toolsetBuildProject + $path = Join-Path $path (Join-Path $buildTool.Framework "Microsoft.DotNet.Arcade.Sdk.dll") + $args += "/logger:$path" + } + + MSBuild-Core @args +} + +# +# Executes msbuild (or 'dotnet msbuild') with arguments passed to the function. +# The arguments are automatically quoted. +# Terminates the script if the build fails. +# +function MSBuild-Core() { if ($ci) { if (!$binaryLog) { throw "Binary log must be enabled in CI build." @@ -476,7 +586,7 @@ function MSBuild() { $exitCode = Exec-Process $buildTool.Path $cmdArgs if ($exitCode -ne 0) { - Write-Host "Build failed." -ForegroundColor Red + Write-PipelineTaskError "Build failed." $buildLog = GetMSBuildBinaryLogCommandLineArgument $args if ($buildLog -ne $null) { @@ -504,6 +614,8 @@ function GetMSBuildBinaryLogCommandLineArgument($arguments) { return $null } +. $PSScriptRoot\LoggingCommandFunctions.ps1 + $RepoRoot = Resolve-Path (Join-Path $PSScriptRoot "..\..") $EngRoot = Resolve-Path (Join-Path $PSScriptRoot "..") $ArtifactsDir = Join-Path $RepoRoot "artifacts" @@ -512,16 +624,15 @@ $ToolsDir = Join-Path $RepoRoot ".tools" $LogDir = Join-Path (Join-Path $ArtifactsDir "log") $configuration $TempDir = Join-Path (Join-Path $ArtifactsDir "tmp") $configuration $GlobalJson = Get-Content -Raw -Path (Join-Path $RepoRoot "global.json") | ConvertFrom-Json +# true if global.json contains a "runtimes" section +$globalJsonHasRuntimes = if ($GlobalJson.tools.PSObject.Properties.Name -Match 'runtimes') { $true } else { $false } Create-Directory $ToolsetDir Create-Directory $TempDir Create-Directory $LogDir -if ($ci) { - Write-Host "##vso[task.setvariable variable=Artifacts]$ArtifactsDir" - Write-Host "##vso[task.setvariable variable=Artifacts.Toolset]$ToolsetDir" - Write-Host "##vso[task.setvariable variable=Artifacts.Log]$LogDir" - - $env:TEMP = $TempDir - $env:TMP = $TempDir -} +Write-PipelineSetVariable -Name 'Artifacts' -Value $ArtifactsDir +Write-PipelineSetVariable -Name 'Artifacts.Toolset' -Value $ToolsetDir +Write-PipelineSetVariable -Name 'Artifacts.Log' -Value $LogDir +Write-PipelineSetVariable -Name 'TEMP' -Value $TempDir +Write-PipelineSetVariable -Name 'TMP' -Value $TempDir diff --git a/eng/common/tools.sh b/eng/common/tools.sh index ecdece1f8552..fd26f6fbb275 100644 --- a/eng/common/tools.sh +++ b/eng/common/tools.sh @@ -1,8 +1,20 @@ +#!/usr/bin/env bash + # Initialize variables if they aren't already defined. # CI mode - set to true on CI server for PR validation build or official build. ci=${ci:-false} +# Set to true to use the pipelines logger which will enable Azure logging output. +# https://github.com/Microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md +# This flag is meant as a temporary opt-opt for the feature while validate it across +# our consumers. It will be deleted in the future. +if [[ "$ci" == true ]]; then + pipelines_log=${pipelines_log:-true} +else + pipelines_log=${pipelines_log:-false} +fi + # Build configuration. Common values include 'Debug' and 'Release', but the repository may use other names. configuration=${configuration:-'Debug'} @@ -40,6 +52,78 @@ else use_global_nuget_cache=${use_global_nuget_cache:-true} fi +function EmitError { + if [[ "$ci" != true ]]; then + echo "$@" >&2 + return + fi + + message_type="error" + sourcepath='' + linenumber='' + columnnumber='' + error_code='' + + while [[ $# -gt 0 ]]; do + opt="$(echo "${1/#--/-}" | awk '{print tolower($0)}')" + case "$opt" in + -type|-t) + message_type=$2 + shift + ;; + -sourcepath|-s) + sourcepath=$2 + shift + ;; + -linenumber|-l) + linenumber=$2 + shift + ;; + -columnnumber|-col) + columnnumber=$2 + shift + ;; + -code|-c) + error_code=$2 + shift + ;; + *) + break + ;; + esac + + shift + done + + message='##vso[task.logissue' + + message="$message type=$message_type" + + if [ -n "$sourcepath" ]; then + message="$message;sourcepath=$sourcepath" + else + message="$message;sourcepath=${BASH_SOURCE[1]}" + fi + + if [ -n "$linenumber" ]; then + message="$message;linenumber=$linenumber" + else + message="$message;linenumber=${BASH_LINENO[0]}" + fi + + if [ -n "$columnnumber" ]; then + message="$message;columnnumber=$columnnumber" + fi + + if [ -n "$error_code" ]; then + message="$message;code=$error_code" + fi + + message="$message]$*" + + echo "$message" +} + # Resolve any symlinks in the given path. function ResolvePath { local path=$1 @@ -65,7 +149,7 @@ function ReadGlobalVersion { local pattern="\"$key\" *: *\"(.*)\"" if [[ ! $line =~ $pattern ]]; then - echo "Error: Cannot find \"$key\" in $global_json_file" >&2 + EmitError "Error: Cannot find \"$key\" in $global_json_file" ExitWithExitCode 1 fi @@ -101,7 +185,7 @@ function InitializeDotNetCli { fi # Find the first path on $PATH that contains the dotnet.exe - if [[ "$use_installed_dotnet_cli" == true && -z "${DOTNET_INSTALL_DIR:-}" ]]; then + if [[ "$use_installed_dotnet_cli" == true && $global_json_has_runtimes == false && -z "${DOTNET_INSTALL_DIR:-}" ]]; then local dotnet_path=`command -v dotnet` if [[ -n "$dotnet_path" ]]; then ResolvePath "$dotnet_path" @@ -115,17 +199,18 @@ function InitializeDotNetCli { # Use dotnet installation specified in DOTNET_INSTALL_DIR if it contains the required SDK version, # otherwise install the dotnet CLI and SDK to repo local .dotnet directory to avoid potential permission issues. - if [[ -n "${DOTNET_INSTALL_DIR:-}" && -d "$DOTNET_INSTALL_DIR/sdk/$dotnet_sdk_version" ]]; then + if [[ $global_json_has_runtimes == false && -n "${DOTNET_INSTALL_DIR:-}" && -d "$DOTNET_INSTALL_DIR/sdk/$dotnet_sdk_version" ]]; then dotnet_root="$DOTNET_INSTALL_DIR" else dotnet_root="$repo_root/.dotnet" + export DOTNET_INSTALL_DIR="$dotnet_root" if [[ ! -d "$DOTNET_INSTALL_DIR/sdk/$dotnet_sdk_version" ]]; then if [[ "$install" == true ]]; then InstallDotNetSdk "$dotnet_root" "$dotnet_sdk_version" else - echo "Unable to find dotnet with SDK version '$dotnet_sdk_version'" >&2 + EmitError "Unable to find dotnet with SDK version '$dotnet_sdk_version'" ExitWithExitCode 1 fi fi @@ -149,18 +234,36 @@ function InitializeDotNetCli { function InstallDotNetSdk { local root=$1 local version=$2 + local architecture="" + if [[ $# == 3 ]]; then + architecture=$3 + fi + InstallDotNet "$root" "$version" $architecture +} +function InstallDotNet { + local root=$1 + local version=$2 + GetDotNetInstallScript "$root" local install_script=$_GetDotNetInstallScript - local arch_arg="" - if [[ $# == 3 ]]; then - arch_arg="--architecture $3" + local archArg='' + if [[ -n "${3:-}" ]]; then + archArg="--architecture $3" + fi + local runtimeArg='' + if [[ -n "${4:-}" ]]; then + runtimeArg="--runtime $4" fi - bash "$install_script" --version $version --install-dir "$root" $arch_arg || { + local skipNonVersionedFilesArg="" + if [[ "$#" -ge "5" ]]; then + skipNonVersionedFilesArg="--skip-non-versioned-files" + fi + bash "$install_script" --version $version --install-dir "$root" $archArg $runtimeArg $skipNonVersionedFilesArg || { local exit_code=$? - echo "Failed to install dotnet SDK (exit code '$exit_code')." >&2 + EmitError "Failed to install dotnet SDK (exit code '$exit_code')." ExitWithExitCode $exit_code } } @@ -197,6 +300,7 @@ function InitializeBuildTool { # return values _InitializeBuildTool="$_InitializeDotNetCli/dotnet" _InitializeBuildToolCommand="msbuild" + _InitializeBuildToolFramework="netcoreapp2.1" } function GetNuGetPackageCachePath { @@ -212,6 +316,17 @@ function GetNuGetPackageCachePath { _GetNuGetPackageCachePath=$NUGET_PACKAGES } +function InitializeNativeTools() { + if grep -Fq "native-tools" $global_json_file + then + local nativeArgs="" + if [[ "$ci" == true ]]; then + nativeArgs="-InstallDirectory $tools_dir" + fi + "$_script_dir/init-tools-native.sh" $nativeArgs + fi +} + function InitializeToolset { if [[ -n "${_InitializeToolset:-}" ]]; then return @@ -234,7 +349,7 @@ function InitializeToolset { fi if [[ "$restore" != true ]]; then - echo "Toolset version $toolsetVersion has not been restored." >&2 + EmitError "Toolset version $toolsetVersion has not been restored." ExitWithExitCode 2 fi @@ -246,12 +361,12 @@ function InitializeToolset { fi echo '' > "$proj" - MSBuild "$proj" $bl /t:__WriteToolsetLocation /clp:ErrorsOnly\;NoSummary /p:__ToolsetLocationOutputFile="$toolset_location_file" + MSBuild-Core "$proj" $bl /t:__WriteToolsetLocation /clp:ErrorsOnly\;NoSummary /p:__ToolsetLocationOutputFile="$toolset_location_file" local toolset_build_proj=`cat "$toolset_location_file"` if [[ ! -a "$toolset_build_proj" ]]; then - echo "Invalid toolset path: $toolset_build_proj" >&2 + EmitError "Invalid toolset path: $toolset_build_proj" ExitWithExitCode 3 fi @@ -274,14 +389,27 @@ function StopProcesses { } function MSBuild { + local args=$@ + if [[ "$pipelines_log" == true ]]; then + InitializeBuildTool + InitializeToolset + local toolset_dir="${_InitializeToolset%/*}" + local logger_path="$toolset_dir/$_InitializeBuildToolFramework/Microsoft.DotNet.Arcade.Sdk.dll" + args=( "${args[@]}" "-logger:$logger_path" ) + fi + + MSBuild-Core ${args[@]} +} + +function MSBuild-Core { if [[ "$ci" == true ]]; then if [[ "$binary_log" != true ]]; then - echo "Binary log must be enabled in CI build." >&2 + EmitError "Binary log must be enabled in CI build." ExitWithExitCode 1 fi if [[ "$node_reuse" == true ]]; then - echo "Node reuse must be disabled in CI build." >&2 + EmitError "Node reuse must be disabled in CI build." ExitWithExitCode 1 fi fi @@ -295,7 +423,7 @@ function MSBuild { "$_InitializeBuildTool" "$_InitializeBuildToolCommand" /m /nologo /clp:Summary /v:$verbosity /nr:$node_reuse $warnaserror_switch /p:TreatWarningsAsErrors=$warn_as_error /p:ContinuousIntegrationBuild=$ci "$@" || { local exit_code=$? - echo "Build failed (exit code '$exit_code')." >&2 + EmitError "Build failed (exit code '$exit_code')." ExitWithExitCode $exit_code } } @@ -307,10 +435,17 @@ eng_root=`cd -P "$_script_dir/.." && pwd` repo_root=`cd -P "$_script_dir/../.." && pwd` artifacts_dir="$repo_root/artifacts" toolset_dir="$artifacts_dir/toolset" +tools_dir="$repo_root/.tools" log_dir="$artifacts_dir/log/$configuration" temp_dir="$artifacts_dir/tmp/$configuration" global_json_file="$repo_root/global.json" +# determine if global.json contains a "runtimes" entry +global_json_has_runtimes=false +dotnetlocal_key=`grep -m 1 "runtimes" "$global_json_file"` || true +if [[ -n "$dotnetlocal_key" ]]; then + global_json_has_runtimes=true +fi # HOME may not be defined in some scenarios, but it is required by NuGet if [[ -z $HOME ]]; then @@ -325,4 +460,4 @@ mkdir -p "$log_dir" if [[ $ci == true ]]; then export TEMP="$temp_dir" export TMP="$temp_dir" -fi +fi \ No newline at end of file diff --git a/eng/configurations/targetgroups.props b/eng/configurations/targetgroups.props index 320103337fdb..5878d40d2532 100644 --- a/eng/configurations/targetgroups.props +++ b/eng/configurations/targetgroups.props @@ -42,7 +42,7 @@ aot true uap10.0.16299aot - uapvnext;netstandard2.0 + uapvnext;netstandard2.1 $(UAPvNextTFM) @@ -50,7 +50,7 @@ $(UAPvNextVersion) true uap10.0.16299 - netstandard2.0 + netstandard2.1 @@ -59,7 +59,7 @@ $(UAPvNextVersion) true uapvnext - netstandard + netstandard2.1 @@ -69,7 +69,7 @@ aot true uapvnextaot - uap;netstandard + uap;netstandard2.1 netstandard1.0 @@ -126,6 +126,13 @@ true netstandard1.6 + + netstandard2.1 + + true + netstandard + netstandard2.0 @@ -157,14 +164,14 @@ 3.0 netcoreapp3.0 netcoreapp2.2 - netstandard + netstandard2.1 3.0 netcoreapp3.0 netcoreapp3.0 - netstandard + netstandard2.1 net45 diff --git a/eng/configure-toolset.ps1 b/eng/configure-toolset.ps1 deleted file mode 100644 index 637e9869e2f7..000000000000 --- a/eng/configure-toolset.ps1 +++ /dev/null @@ -1,5 +0,0 @@ -# We depend on a local cli for a number of our buildtool -# commands like init-tools so for now we need to disable -# using the globally installed dotnet - -$script:useInstalledDotNetCli = $false diff --git a/eng/configure-toolset.sh b/eng/configure-toolset.sh deleted file mode 100644 index 267c180859f8..000000000000 --- a/eng/configure-toolset.sh +++ /dev/null @@ -1,5 +0,0 @@ -# We depend on a local cli for a number of our buildtool -# commands like init-tools so for now we need to disable -# using the globally installed dotnet - -useInstalledDotNetCli=false \ No newline at end of file diff --git a/eng/depProj.targets b/eng/depProj.targets index 11b70d940762..ce8fcd6b06f3 100644 --- a/eng/depProj.targets +++ b/eng/depProj.targets @@ -111,6 +111,13 @@ See the LICENSE file in the project root for more information. + + + + + + - c86a1e0c3659a3046d43dc278e9711cd23002d97 - c86a1e0c3659a3046d43dc278e9711cd23002d97 - 8bd1ec5fac9f0eec34ff6b34b1d878b4359e02dd - - - - - - 4.4.0 + 9fc9c2df2bf2681e69651664461887c759d0e1e5 - beta-27612-00 - beta-27612-00 - 1.0.0-beta-27612-00 - - - 4.4.0 - - - 16.0.1 - 2.4.1-pre.build.4059 - 1.0.0-beta-build0020 - 2.0.5 - 1.0.31 - - - 1.4.0 - 4.0.5 - - 4.6.0-alpha-00001 - $(ProjectNTfsTestILCPackageVersion) - $(ProjectNTfsTestILCPackageVersion) - $(ProjectNTfsTestILCPackageVersion) - - - - - Microsoft.SymbolUploader.Build.Task - 1.0.0-beta-63604-05 + beta-27731-00 @@ -60,18 +25,10 @@ - - $(BaseDotNetBuildInfo)sni/$(DependencyBranch) - $(SniCurrentRef) - $(BaseDotNetBuildInfo)projectn-tfs/$(DependencyBranch) $(ProjectNTfsCurrentRef) - - $(BaseDotNetBuildInfo)projectn-tfs-testilc/$(DependencyBranch) - $(ProjectNTfsTestILCCurrentRef) - https://raw.githubusercontent.com/dotnet/versions @@ -82,61 +39,5 @@ ProjectNTfsExpectedPrerelease ProjectNTfs - - $(MSBuildThisFileFullPath) - ProjectNTfsTestILCExpectedPrerelease - ProjectNTfsTestILC - - - $(MSBuildThisFileFullPath) - ProjectNTfsTestILCPackageVersion - TestILC.amd64ret - - - $(MSBuildThisFileFullPath) - RuntimeWinX64RuntimeNativeSystemDataSqlClientSniPackageVersion - runtime.win-x64.runtime.native.System.Data.SqlClient.sni - - - - - - - - - - - - 1.0.1 - - - - 1.0.5 - - - - - - - $(XUnitPackageVersion) - - - - - - - - $(XUnitPerformancePackageVersion) - - - - %(Identity) - true - - - - - diff --git a/eng/dir.traversal.targets b/eng/dir.traversal.targets index c9bbb50c019e..e5f0f1b2cf2a 100644 --- a/eng/dir.traversal.targets +++ b/eng/dir.traversal.targets @@ -1,32 +1,6 @@ - + - - - - - - - - - - - - - - - - $(MSBuildProjectDefaultTargets) diff --git a/eng/internal/NuGet.config b/eng/internal/NuGet.config index f3a94002b19a..885f44c10936 100644 --- a/eng/internal/NuGet.config +++ b/eng/internal/NuGet.config @@ -7,7 +7,6 @@ - diff --git a/eng/pipelines/corefx-base.yml b/eng/pipelines/corefx-base.yml index 67a02a0391a3..9f98999bded1 100644 --- a/eng/pipelines/corefx-base.yml +++ b/eng/pipelines/corefx-base.yml @@ -22,8 +22,8 @@ parameters: # _framework: (netcoreapp, netfx, uap, etc). # _helixQueues: Windows.Amd64 (Only needed if submitToHelix -> true.) -- Queues should be separated by + if multiple. - # Required: as part of the variables object, the following values need to be passed: - # _outerloop: true | false + # Required: empty | innerloop | outerloop | all + testScope: '' # Optional: _publishTests -> Boolean -> Publish test assets to blob storage if true. # Default: false @@ -75,6 +75,10 @@ jobs: - _msbuildCommonParameters: '' - _archiveTestsParameter: '' - _finalFrameworkArg: -framework $(_framework) + - _testScopeArg: '' + + - ${{ if ne(parameters.testScope, '') }}: + - _testScopeArg: -testscope ${{ parameters.testScope }} - ${{ if ne(job._jobFramework, '')}}: - _finalFrameworkArg: ${{ job._jobFramework }} @@ -142,15 +146,13 @@ jobs: restoreDirectory: '$(Build.SourcesDirectory)\.packages' verbosityRestore: 'normal' externalFeedCredentials: 'dotnet-core-internal-tooling' - env: - TargetGroup: $(_framework) - ${{ if eq(job.customBuildSteps[0], '') }}: - script: $(_buildScript) -build -buildtests $(_commonArguments) - /p:OuterLoop=$(_outerloop) + $(_testScopeArg) $(_msbuildCommonParameters) displayName: Build Sources and Tests @@ -189,26 +191,23 @@ jobs: - template: /eng/pipelines/helix.yml parameters: + # send tests to helix only on public builds, official scheduled builds or manual official builds. + condition: eq(${{ parameters.isOfficialBuild }}, False) targetOS: ${{ parameters.targetOS }} archGroup: $(_architecture) configuration: $(_BuildConfig) helixQueues: $(_helixQueues) msbuildScript: $(_msbuildCommand) framework: $(_framework) - outerloop: $(_outerloop) - enableAzurePipelinesReporter: false + testScope: ${{ parameters.testScope }} ${{ if eq(parameters.isOfficialBuild, 'true') }}: - isExternal: false - waitForCompletion: false officialBuildId: $(Build.BuildNumber) helixToken: $(HelixApiAccessToken) ${{ if eq(parameters.isOfficialBuild, 'false') }}: # TODO: SET Creator to the PR owner whenever Azure DevOps supports a good way to retrieve it. creator: dotnet-bot - isExternal: true - waitForCompletion: true helixToken: '' - ${{ if eq(parameters.isOfficialBuild, 'true') }}: diff --git a/eng/pipelines/freebsd.yml b/eng/pipelines/freebsd.yml index 4f35c108455f..5c18391311ee 100644 --- a/eng/pipelines/freebsd.yml +++ b/eng/pipelines/freebsd.yml @@ -1,9 +1,20 @@ -# FreeBSD leg. Only for used in Official Builds +# FreeBSD leg +parameters: + # Required: value to specify if the job is comming from an official build to run extra steps and sign binaries + # Default: false + isOfficialBuild: false + # Required: value to specify if the full test matrix should be tested + # Default: false + fullMatrix: false + # Optional: value to scope the tests. + # Default: empty + testScope: '' jobs: - template: corefx-base.yml parameters: - isOfficialBuild: true + isOfficialBuild: ${{ parameters.isOfficialBuild }} + testScope: ${{ parameters.testScope }} targetOS: FreeBSD jobs: @@ -21,7 +32,3 @@ jobs: buildScriptPrefix: $(_buildScriptPrefix) submitToHelix: false - - variables: - - _skipTests: true - - _outerloop: true # Only runs in official builds diff --git a/eng/pipelines/helix.yml b/eng/pipelines/helix.yml index b6395d277952..b1f0c74396f9 100644 --- a/eng/pipelines/helix.yml +++ b/eng/pipelines/helix.yml @@ -5,13 +5,11 @@ parameters: framework: '' helixQueues: '' helixToken: '' - isExternal: '' # true | false msbuildScript: '' targetOS: '' - waitForCompletion: '' # true | false officialBuildId: '' - enableAzurePipelinesReporter: '' # true | false - outerloop: '' # true | false + testScope: '' # empty | innerloop | outerloop | all + condition: always() steps: - script: ${{ parameters.msbuildScript }} @@ -20,17 +18,15 @@ steps: /p:ArchGroup=${{ parameters.archGroup }} /p:ConfigurationGroup=${{ parameters.configuration }} /p:OSGroup=${{ parameters.targetOS }} - /p:OuterLoop=${{ parameters.outerloop }} + /p:testScope=${{ parameters.testScope }} /p:TargetGroup=${{ parameters.framework }} /p:HelixTargetQueues=${{ parameters.helixQueues }} /p:HelixBuild=$(Build.BuildNumber) /p:HelixAccessToken=${{ parameters.helixToken }} - /p:WaitForWorkItemCompletion=${{ parameters.waitForCompletion }} - /p:IsExternal=${{ parameters.isExternal }} /p:Creator=${{ parameters.creator }} /p:OfficialBuildId=${{ parameters.officialBuildId }} - /p:EnableAzurePipelinesReporter=${{ parameters.enableAzurePipelinesReporter }} /bl:$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)/SendToHelix.binlog displayName: Send to Helix + condition: and(succeeded(), ${{ parameters.condition }}) env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) # We need to set this env var to publish helix results to Azure Dev Ops diff --git a/eng/pipelines/linux.yml b/eng/pipelines/linux.yml index 2b623afeb34c..49c1e60cf544 100644 --- a/eng/pipelines/linux.yml +++ b/eng/pipelines/linux.yml @@ -3,15 +3,18 @@ parameters: # Required: value to specify if the job is comming from an official build to run extra steps and sign binaries # Default: false isOfficialBuild: false - # Required: value to specify if the build is comming from an outerloop pipeline. + # Required: value to specify if the full test matrix should be tested # Default: false - isOuterloopBuild: false + fullMatrix: false + # Optional: value to scope the tests. + # Default: empty + testScope: '' jobs: - - template: corefx-base.yml parameters: isOfficialBuild: ${{ parameters.isOfficialBuild }} + testScope: ${{ parameters.testScope }} targetOS: Linux jobs: @@ -38,6 +41,7 @@ jobs: _dockerContainer: ubuntu_1604_arm64_cross_container _buildScriptPrefix: 'ROOTFS_DIR=/crossrootfs/arm64 ' _buildExtraArguments: -warnAsError false + _publishTests: true musl_x64_Release: _BuildConfig: Release @@ -47,8 +51,9 @@ jobs: _dockerContainer: alpine_36_container _buildScriptPrefix: '' _buildExtraArguments: /p:RuntimeOS=linux-musl + _publishTests: true - ${{ if eq(parameters.isOuterloopBuild, 'true') }}: + ${{ if or(eq(parameters.testScope, 'outerloop'), eq(parameters.testScope, 'all')) }}: x64_Debug: _BuildConfig: Debug _architecture: x64 @@ -76,7 +81,7 @@ jobs: _buildScriptPrefix: '' _buildExtraArguments: /p:RuntimeOS=linux-musl - ${{ if eq(parameters.isOfficialBuild, 'true') }}: + ${{ if eq(parameters.fullMatrix, 'true') }}: arm_Release: _BuildConfig: Release _architecture: arm @@ -85,6 +90,7 @@ jobs: _dockerContainer: ubuntu_1604_arm_cross_container _buildScriptPrefix: 'ROOTFS_DIR=/crossrootfs/arm ' _buildExtraArguments: -warnAsError false + _publishTests: true musl_arm64_Release: _BuildConfig: Release @@ -94,6 +100,7 @@ jobs: _dockerContainer: alpine_37_arm64_container _buildScriptPrefix: 'ROOTFS_DIR=/crossrootfs/arm64 ' _buildExtraArguments: -warnAsError false /p:BuildNativeCompiler=--clang5.0 /p:RuntimeOS=linux-musl + _publishTests: true pool: name: Hosted Ubuntu 1604 @@ -104,26 +111,21 @@ jobs: submitToHelix: true variables: - - _skipTests: true - - _outerloop: ${{ parameters.isOfficialBuild }} - - ${{ if eq(parameters.isOuterloopBuild, 'true') }}: - - _outerloop: true - - - ${{ if eq(parameters.isOfficialBuild, 'false') }}: - - linuxDefaultQueues: Centos.7.Amd64.Open+RedHat.7.Amd64.Open+Debian.8.Amd64.Open+Ubuntu.1604.Amd64.Open+Ubuntu.1804.Amd64.Open+OpenSuse.42.Amd64.Open+\(Fedora.28.Amd64\)ubuntu.1604.amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:fedora-28-helix-45b1fa2-20190402012449 - - linuxArm64Queues: \(Ubuntu.1604.Arm64\)Ubuntu.1604.Arm64.Docker.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-16.04-helix-arm64v8-b049512-20190321153539 - - alpineQueues: \(Alpine.38.Amd64\)ubuntu.1604.amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:alpine-3.8-helix-45b1fa2-20190327215821 - - - ${{ if eq(parameters.isOfficialBuild, 'true') }}: - - linuxDefaultQueues: Centos.7.Amd64+RedHat.7.Amd64+Debian.8.Amd64+Debian.9.Amd64+Ubuntu.1604.Amd64+Ubuntu.1804.Amd64+Ubuntu.1810.Amd64+OpenSuse.42.Amd64+SLES.12.Amd64+SLES.15.Amd64+\(Fedora.28.Amd64\)ubuntu.1604.amd64@mcr.microsoft.com/dotnet-buildtools/prereqs:fedora-28-helix-45b1fa2-20190402012449+\(Fedora.29.Amd64\)ubuntu.1604.amd64@mcr.microsoft.com/dotnet-buildtools/prereqs:fedora-29-helix-c6dc5e6-20190402012449 - - linuxArm64Queues: \(Ubuntu.1604.Arm64\)Ubuntu.1604.Arm64.Docker@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-16.04-helix-arm64v8-b049512-20190321153539 - - linuxArmQueues: \(Debian.9.Arm32\)Ubuntu.1604.Arm32@mcr.microsoft.com/dotnet-buildtools/prereqs:debian-9-helix-arm32v7-b049512-20190321153542 - - alpineQueues: \(Alpine.38.Amd64\)ubuntu.1604.amd64@mcr.microsoft.com/dotnet-buildtools/prereqs:alpine-3.8-helix-45b1fa2-20190327215821+\(Alpine.39.Amd64\)ubuntu.1604.amd64@mcr.microsoft.com/dotnet-buildtools/prereqs:alpine-3.9-helix-e4eaef4-20190228230637 - - alpineArm64Queues: \(Alpine.38.Arm64\)Ubuntu.1604.Arm64.Docker@mcr.microsoft.com/dotnet-buildtools/prereqs:alpine-3.8-helix-arm64v8-46e69dd-20190327215724 + - linuxArm64Queues: \(Ubuntu.1604.Arm64.Open\)Ubuntu.1604.Arm64.Docker.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-16.04-helix-arm64v8-b049512-20190321153539 + + - ${{ if eq(parameters.fullMatrix, 'false') }}: + - linuxDefaultQueues: Centos.7.Amd64.Open+RedHat.7.Amd64.Open+Debian.8.Amd64.Open+Ubuntu.1604.Amd64.Open+Ubuntu.1804.Amd64.Open+OpenSuse.42.Amd64.Open+\(Fedora.28.Amd64.Open\)ubuntu.1604.amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:fedora-28-helix-09ca40b-20190508143249 + - alpineQueues: \(Alpine.39.Amd64.Open\)ubuntu.1604.amd64.open@mcr.microsoft.com/dotnet-buildtools/prereqs:alpine-3.9-helix-09ca40b-20190508143246 + + - ${{ if eq(parameters.fullMatrix, 'true') }}: + - linuxDefaultQueues: Centos.7.Amd64.Open+RedHat.7.Amd64.Open+Debian.8.Amd64.Open+Debian.9.Amd64.Open+Ubuntu.1604.Amd64.Open+Ubuntu.1804.Amd64.Open+Ubuntu.1810.Amd64.Open+OpenSuse.42.Amd64.Open+SLES.12.Amd64.Open+SLES.15.Amd64.Open+\(Fedora.28.Amd64.Open\)ubuntu.1604.amd64.open@mcr.microsoft.com/dotnet-buildtools/prereqs:fedora-28-helix-09ca40b-20190508143249+\(Fedora.29.Amd64.Open\)ubuntu.1604.amd64.open@mcr.microsoft.com/dotnet-buildtools/prereqs:fedora-29-09ca40b-20190508143249+\(Ubuntu.1904.Amd64.Open\)ubuntu.1604.amd64.open@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-19.04-helix-amd64-09ca40b-20190508143257 + - linuxArmQueues: \(Debian.9.Arm32.Open\)Ubuntu.1604.Arm32.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:debian-9-helix-arm32v7-b049512-20190321153542 + - alpineQueues: \(Alpine.38.Amd64.Open\)ubuntu.1604.amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:alpine-3.8-helix-09ca40b-20190508143246+\(Alpine.39.Amd64.Open\)ubuntu.1604.amd64.open@mcr.microsoft.com/dotnet-buildtools/prereqs:alpine-3.9-helix-09ca40b-20190508143246 + - alpineArm64Queues: \(Alpine.38.Arm64.Open\)Ubuntu.1604.Arm64.Docker.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:alpine-3.8-helix-arm64v8-46e69dd-20190327215724 # Legs without helix testing # Only run this leg in PRs. - - ${{ if and(eq(parameters.isOfficialBuild, 'false'), eq(parameters.isOuterloopBuild, 'false')) }}: + - ${{ if and(eq(parameters.isOfficialBuild, 'false'), and(ne(parameters.testScope, 'outerloop'), ne(parameters.testScope, 'all'))) }}: - job: LinuxNoTest displayName: Linux strategy: @@ -151,7 +153,3 @@ jobs: buildExtraArguments: $(_buildExtraArguments) buildScriptPrefix: $(_buildScriptPrefix) submitToHelix: false - - variables: - - _skipTests: true - - _outerloop: ${{ parameters.isOfficialBuild }} diff --git a/eng/pipelines/macos.yml b/eng/pipelines/macos.yml index 5c1d0c1d67d0..779b9a2c5837 100644 --- a/eng/pipelines/macos.yml +++ b/eng/pipelines/macos.yml @@ -3,15 +3,18 @@ parameters: # Required: value to specify if the job is comming from an official build to run extra steps and sign binaries # Default: false isOfficialBuild: false - # Required: value to specify if the build is comming from an outerloop pipeline. + # Required: value to specify if the full test matrix should be tested # Default: false - isOuterloopBuild: false + fullMatrix: false + # Optional: value to scope the tests. + # Default: empty + testScope: '' jobs: - - template: corefx-base.yml parameters: isOfficialBuild: ${{ parameters.isOfficialBuild }} + testScope: ${{ parameters.testScope }} targetOS: OSX jobs: @@ -20,14 +23,14 @@ jobs: displayName: MacOS strategy: matrix: - ${{ if eq(parameters.isOfficialBuild, 'false') }}: + ${{ if eq(parameters.fullMatrix, 'false') }}: x64_Debug: _BuildConfig: Debug _architecture: x64 _framework: netcoreapp _helixQueues: $(macOSQueues) - ${{ if eq(parameters.isOfficialBuild, 'true') }}: + ${{ if eq(parameters.fullMatrix, 'true') }}: x64_Release: _BuildConfig: Release _architecture: x64 @@ -49,13 +52,8 @@ jobs: submitToHelix: true variables: - - _skipTests: true - - _outerloop: ${{ parameters.isOfficialBuild }} - - ${{ if eq(parameters.isOuterloopBuild, 'true') }}: - - _outerloop: true - - ${{ if eq(parameters.isOfficialBuild, 'false') }}: - macOSQueues: OSX.1012.Amd64.Open+OSX.1013.Amd64.Open - ${{ if eq(parameters.isOfficialBuild, 'true') }}: - - macOSQueues: OSX.1012.Amd64+OSX.1013.Amd64+OSX.1014.Amd64 + - macOSQueues: OSX.1012.Amd64.Open+OSX.1013.Amd64.Open+OSX.1014.Amd64.Open diff --git a/eng/pipelines/outerloop.yml b/eng/pipelines/outerloop.yml index e3222799f409..3dc88a70cb79 100644 --- a/eng/pipelines/outerloop.yml +++ b/eng/pipelines/outerloop.yml @@ -5,27 +5,42 @@ resources: - container: rhel7_container image: microsoft/dotnet-buildtools-prereqs:rhel7_prereqs_2 - - container: ubuntu_1604_arm64_cross_container - image: microsoft/dotnet-buildtools-prereqs:ubuntu-16.04-cross-arm64-a3ae44b-20180315221921 + - container: rhel6_container + image: microsoft/dotnet-buildtools-prereqs:centos-6-376e1a3-20174311014331 - container: alpine_36_container image: microsoft/dotnet-buildtools-prereqs:alpine-3.6-WithNode-f4d3fe3-20181213005010 + - container: alpine_37_arm64_container + image: microsoft/dotnet-buildtools-prereqs:ubuntu-16.04-cross-arm64-alpine10fcdcf-20190208200917 + + - container: ubuntu_1604_arm64_cross_container + image: microsoft/dotnet-buildtools-prereqs:ubuntu-16.04-cross-arm64-a3ae44b-20180315221921 + + - container: ubuntu_1604_arm_cross_container + image: microsoft/dotnet-buildtools-prereqs:ubuntu-16.04-cross-ef0ac75-20175511035548 + jobs: # Windows outerloop legs - - ${{ if endsWith(variables['Build.DefinitionName'], 'windows') }}: + - ${{ if or(endsWith(variables['Build.DefinitionName'], 'windows'), endsWith(variables['Build.DefinitionName'], 'outerloop')) }}: - template: /eng/pipelines/windows.yml parameters: - isOuterloopBuild: true + isOfficialBuild: ${{ and(ne(variables['System.TeamProject'], 'public'), notIn(variables['Build.Reason'], 'PullRequest')) }} + fullMatrix: ${{ notIn(variables['Build.Reason'], 'PullRequest') }} + testScope: outerloop # Linux outerloop legs - - ${{ if endsWith(variables['Build.DefinitionName'], 'linux') }}: + - ${{ if or(endsWith(variables['Build.DefinitionName'], 'linux'), endsWith(variables['Build.DefinitionName'], 'outerloop')) }}: - template: /eng/pipelines/linux.yml parameters: - isOuterloopBuild: true + isOfficialBuild: ${{ and(ne(variables['System.TeamProject'], 'public'), notIn(variables['Build.Reason'], 'PullRequest')) }} + fullMatrix: ${{ notIn(variables['Build.Reason'], 'PullRequest') }} + testScope: outerloop # MacOS outerloop legs - - ${{ if endsWith(variables['Build.DefinitionName'], 'osx') }}: + - ${{ if or(endsWith(variables['Build.DefinitionName'], 'osx'), endsWith(variables['Build.DefinitionName'], 'outerloop')) }}: - template: /eng/pipelines/macos.yml parameters: - isOuterloopBuild: true \ No newline at end of file + isOfficialBuild: ${{ and(ne(variables['System.TeamProject'], 'public'), notIn(variables['Build.Reason'], 'PullRequest')) }} + fullMatrix: ${{ notIn(variables['Build.Reason'], 'PullRequest') }} + testScope: outerloop \ No newline at end of file diff --git a/eng/pipelines/publish.yml b/eng/pipelines/publish.yml index 7813515ffac2..6080e752ad85 100644 --- a/eng/pipelines/publish.yml +++ b/eng/pipelines/publish.yml @@ -16,7 +16,7 @@ jobs: dependsOn: ${{ parameters.dependsOn }} pool: - name: NetCoreInternal-Int-Pool + name: NetCoreInternal-Pool queue: buildpool.windows.10.amd64.vs2017 workspace: @@ -112,7 +112,7 @@ jobs: dependsOn: ${{ parameters.dependsOn }} pool: - name: NetCoreInternal-Int-Pool + name: NetCoreInternal-Pool queue: buildpool.windows.10.amd64.vs2017 workspace: diff --git a/eng/pipelines/redhat6.yml b/eng/pipelines/redhat6.yml index 52cc6eb20a35..af7f71776274 100644 --- a/eng/pipelines/redhat6.yml +++ b/eng/pipelines/redhat6.yml @@ -1,9 +1,20 @@ -# RedHat 6 leg. Only for used in Official Builds +# RedHat 6 leg +parameters: + # Required: value to specify if the job is comming from an official build to run extra steps and sign binaries + # Default: false + isOfficialBuild: false + # Required: value to specify if the full test matrix should be tested + # Default: false + fullMatrix: false + # Optional: value to scope the tests. + # Default: empty + testScope: '' jobs: - template: corefx-base.yml parameters: - isOfficialBuild: true + isOfficialBuild: ${{ parameters.isOfficialBuild }} + testScope: ${{ parameters.testScope }} targetOS: Linux jobs: @@ -26,6 +37,4 @@ jobs: submitToHelix: true variables: - - _skipTests: true - - _outerloop: true # Only runs in official builds - - redhatHelixQueue: RedHat.6.Amd64 + - redhatHelixQueue: RedHat.6.Amd64.Open diff --git a/eng/pipelines/windows.yml b/eng/pipelines/windows.yml index b165a2ae837e..30cffd3d6ed5 100644 --- a/eng/pipelines/windows.yml +++ b/eng/pipelines/windows.yml @@ -3,15 +3,19 @@ parameters: # Required: value to specify if the job is comming from an official build to run extra steps and sign binaries # Default: false isOfficialBuild: false - # Required: value to specify if the build is comming from an outerloop pipeline. + # Required: value to specify if the full test matrix should be tested # Default: false - isOuterloopBuild: false + fullMatrix: false + # Optional: value to scope the tests. + # Default: empty + testScope: '' jobs: - template: corefx-base.yml parameters: isOfficialBuild: ${{ parameters.isOfficialBuild }} + testScope: ${{ parameters.testScope }} targetOS: Windows_NT jobs: @@ -21,7 +25,7 @@ jobs: strategy: matrix: # PR CI Matrix - ${{ if eq(parameters.isOfficialBuild, 'false') }}: + ${{ if eq(parameters.fullMatrix, 'false') }}: x64_Debug: _BuildConfig: Debug _architecture: x64 @@ -46,9 +50,18 @@ jobs: _architecture: x64 _framework: uap _helixQueues: $(uapNetfxQueues) + + # Run arm on the matrix or in Outerloop + ${{ if or(eq(parameters.fullMatrix, 'true'), or(eq(parameters.testScope, 'outerloop'), eq(parameters.testScope, 'all'))) }}: + arm64_Release: + _BuildConfig: Release + _architecture: arm64 + _framework: netcoreapp + _helixQueues: $(windowsArmQueue) + _publishTests: true - # Official build LEGS with HELIX Testing - ${{ if eq(parameters.isOfficialBuild, 'true') }}: + # Full test matrix + ${{ if eq(parameters.fullMatrix, 'true') }}: x64_Release: _BuildConfig: Release _architecture: x64 @@ -63,13 +76,6 @@ jobs: _helixQueues: $(netcoreappWindowsQueues) _publishTests: true - arm64_Release: - _BuildConfig: Release - _architecture: arm64 - _framework: netcoreapp - _helixQueues: $(windowsArmQueue) - _publishTests: true - NETFX_x86_Release: _BuildConfig: Release _architecture: x86 @@ -96,54 +102,32 @@ jobs: _framework: uap _helixQueues: $(uapNetfxQueues) - UAPAOT_x86_Release: - _BuildConfig: Release - _architecture: x86 - _framework: uapaot - _helixQueues: $(uapNetfxQueues) - - UAPAOT_x64_Release: - _BuildConfig: Release - _architecture: x64 - _framework: uapaot - _helixQueues: $(uapNetfxQueues) - pool: - ${{ if eq(parameters.isOfficialBuild, 'true') }}: - name: NetCoreInternal-Int-Pool - queue: buildpool.windows.10.amd64.vs2017 - ${{ if eq(parameters.isOfficialBuild, 'false') }}: - name: Hosted VS2017 + name: Hosted VS2017 submitToHelix: true buildExtraArguments: /p:RuntimeOS=win10 variables: - - _skipTests: true - - _outerloop: ${{ parameters.isOfficialBuild }} - - ${{ if eq(parameters.isOuterloopBuild, 'true') }}: - - _outerloop: true + - nanoQueues: "`(Windows.Nano.1803.Amd64.Open`)windows.10.amd64.serverrs4.open@mcr.microsoft.com/dotnet-buildtools/prereqs:nanoserver-1803-helix-amd64-05227e1-20190509225944" + - uapNetfxQueues: Windows.10.Amd64.ClientRS5.Open + - windowsArmQueue: Windows.10.Arm64.Open - - ${{ if eq(parameters.isOfficialBuild, 'false') }}: + - ${{ if eq(parameters.fullMatrix, 'false') }}: - netcoreappWindowsQueues: Windows.7.Amd64.Open+Windows.81.Amd64.Open+Windows.10.Amd64.ClientRS4.ES.Open - - nanoQueues: Windows.10.Nano.Amd64.Open - - uapNetfxQueues: Windows.10.Amd64.ClientRS5.Open - - ${{ if eq(parameters.isOfficialBuild, 'true') }}: - - netcoreappWindowsQueues: Windows.7.Amd64+Windows.81.Amd64+Windows.10.Amd64.Core+Windows.10.Amd64.ClientRS4 - - nanoQueues: Windows.10.Nano.Amd64 - - uapNetfxQueues: Windows.10.Amd64.ClientRS5 - - windowsArmQueue: Windows.10.Arm64 + - ${{ if eq(parameters.fullMatrix, 'true') }}: + - netcoreappWindowsQueues: Windows.7.Amd64.Open+Windows.81.Amd64.Open+Windows.10.Amd64.ClientRS4.Open+Windows.10.Amd64.ServerRS5.Open # There is no point of running legs without outerloop tests, when in an outerloop build. - - ${{ if eq(parameters.isOuterloopBuild, 'false') }}: + - ${{ if and(ne(parameters.testScope, 'outerloop'), ne(parameters.testScope, 'all')) }}: # Packaging all configurations - job: AllConfigurations displayName: Packaging All Configurations strategy: matrix: # PR Validation Matrix - ${{ if eq(parameters.isOfficialBuild, 'false') }}: + ${{ if eq(parameters.fullMatrix, 'false') }}: x64_Debug: _BuildConfig: Debug _architecture: x64 @@ -151,7 +135,7 @@ jobs: _helixQueues: $(allConfigurationsQueues) # Official Build Matrix - ${{ if eq(parameters.isOfficialBuild, 'true') }}: + ${{ if eq(parameters.fullMatrix, 'true') }}: x64_Release: _BuildConfig: Release _architecture: x64 @@ -159,23 +143,13 @@ jobs: _helixQueues: $(allConfigurationsQueues) pool: - ${{ if eq(parameters.isOfficialBuild, 'true') }}: - name: NetCoreInternal-Int-Pool - queue: buildpool.windows.10.amd64.vs2017 - ${{ if eq(parameters.isOfficialBuild, 'false') }}: - name: Hosted VS2017 + name: Hosted VS2017 submitToHelix: true buildExtraArguments: /p:RuntimeOS=win10 - # azure pipelines reporter only supports xunit results based tests. - enableAzurePipelinesReporter: false variables: - - _outerloop: false - - ${{ if eq(parameters.isOfficialBuild, 'false') }}: - - allConfigurationsQueues: Windows.10.Amd64.ClientRS5.Open - - ${{ if eq(parameters.isOfficialBuild, 'true') }}: - - allConfigurationsQueues: Windows.10.Amd64.ClientRS5 + - allConfigurationsQueues: Windows.10.Amd64.ClientRS5.Open _jobFramework: -allConfigurations customBuildSteps: @@ -191,19 +165,18 @@ jobs: $(_msbuildCommonParameters) displayName: Build Packages and Tests - # TODO: UAPAOT official builds should send to helix using continuation runner. # Legs without HELIX testing - job: WindowsNoTest displayName: Windows strategy: matrix: - ${{ if eq(parameters.isOfficialBuild, 'false') }}: + ${{ if eq(parameters.fullMatrix, 'false') }}: UWP_NETNative_x86_Release: _BuildConfig: Release _architecture: x86 _framework: uapaot - ${{ if eq(parameters.isOfficialBuild, 'true') }}: + ${{ if eq(parameters.fullMatrix, 'true') }}: arm_Release: _BuildConfig: Release _architecture: arm @@ -214,26 +187,8 @@ jobs: _architecture: arm _framework: uap - UAPAOT_arm_Release: - _BuildConfig: Release - _architecture: arm - _framework: uapaot - - UAPAOT_arm64_Release: - _BuildConfig: Release - _architecture: arm64 - _framework: uapaot - pool: - ${{ if eq(parameters.isOfficialBuild, 'true') }}: - name: NetCoreInternal-Int-Pool - queue: buildpool.windows.10.amd64.vs2017 - ${{ if eq(parameters.isOfficialBuild, 'false') }}: - name: Hosted VS2017 + name: Hosted VS2017 submitToHelix: false buildExtraArguments: /p:RuntimeOS=win10 - - variables: - - _skipTests: true - - _outerloop: ${{ parameters.isOfficialBuild }} diff --git a/eng/publish.proj b/eng/publish.proj index 439dffa16f17..e2c970d4a2b7 100644 --- a/eng/publish.proj +++ b/eng/publish.proj @@ -1,6 +1,6 @@ - + @@ -135,7 +135,8 @@ ManifestCommit="$(ManifestCommit)" ManifestBuildData="$(ManifestBuildData)" ManifestRepoUri="$(ManifestRepoUri)" - AssetManifestPath="$(AssetManifestFilePath)" /> + AssetManifestPath="$(AssetManifestFilePath)" + Overwrite="true" /> <_ManifestToPush Remove="@(_ManifestToPush)" /> @@ -155,6 +156,7 @@ ManifestCommit="$(ManifestCommit)" ManifestBuildData="$(ManifestBuildData)" ManifestRepoUri="$(ManifestRepoUri)" - AssetManifestPath="$(AssetManifestDir)ManifestUpload.xml" /> + AssetManifestPath="$(AssetManifestDir)ManifestUpload.xml" + Overwrite="true" /> diff --git a/eng/references.props b/eng/references.props new file mode 100644 index 000000000000..9c65f4210c84 --- /dev/null +++ b/eng/references.props @@ -0,0 +1,10 @@ + + + + $(AssemblySearchPaths);$(RefPath);{RawFileName} + + \ No newline at end of file diff --git a/eng/references.targets b/eng/references.targets index de6eccf63382..f559f1f8adeb 100644 --- a/eng/references.targets +++ b/eng/references.targets @@ -1,8 +1,8 @@ - $(RefPath) - $(ContractOutputPath) - $(AssemblySearchPaths);$(ContractOutputPath);{RawFileName} + $(RefPath) + $(RefPath) + $(AssemblySearchPaths);$(RefPath);{RawFileName} <_FindDependencies>false + false @@ -17,7 +20,13 @@ - - + + + + False + \ No newline at end of file diff --git a/run-test.sh b/eng/run-test.sh old mode 100755 new mode 100644 similarity index 71% rename from run-test.sh rename to eng/run-test.sh index c54987063924..b8f694b94e44 --- a/run-test.sh +++ b/eng/run-test.sh @@ -15,21 +15,21 @@ wait_on_pids() usage() { - echo "Runs .NET CoreFX tests on FreeBSD, Linux, NetBSD or OSX" + echo "Runs .NET CoreFX tests on FreeBSD, NetBSD or Linux" echo "usage: run-test [options]" echo echo "Input sources:" echo " --runtime Location of root of the binaries directory" - echo " containing the FreeBSD, Linux, NetBSD or OSX runtime" + echo " containing the FreeBSD, NetBSD or Linux runtime" echo " default: /bin/testhost/netcoreapp---" echo " --corefx-tests Location of the root binaries location containing" echo " the tests to run" - echo " default: /bin" + echo " default: /artifacts/bin" echo echo "Flavor/OS/Architecture options:" echo " --configurationGroup ConfigurationGroup to run (Debug/Release)" echo " default: Debug" - echo " --os OS to run (FreeBSD, Linux, NetBSD or OSX)" + echo " --os OS to run (FreeBSD, NetBSD or Linux)" echo " default: detect current OS" echo " --arch Architecture to run (x64, arm, armel, x86, arm64)" echo " default: detect current architecture" @@ -47,14 +47,6 @@ usage() echo " listed one line, relative to the directory specified by --corefx-tests" echo " --timeout diff --git a/external/ILLink/ILLink.depproj b/external/ILLink/ILLink.depproj index 5049897cd56f..7f13db572f27 100644 --- a/external/ILLink/ILLink.depproj +++ b/external/ILLink/ILLink.depproj @@ -14,14 +14,14 @@ - + $(ILLinkTasksPackageId) $(ILLinkTasksPackageVersion) /netcoreapp2.0/ - + $(ILLinkTasksPackageId) $(ILLinkTasksPackageVersion) /net46/ diff --git a/external/binplacePackages/binplacePackages.depproj b/external/binplacePackages/binplacePackages.depproj index 0f6da524ca17..8f1984117221 100644 --- a/external/binplacePackages/binplacePackages.depproj +++ b/external/binplacePackages/binplacePackages.depproj @@ -4,6 +4,7 @@ true $(TargetFramework.SubString(11)) Reference + true @@ -29,11 +30,15 @@ - 4.5.1 + 4.5.3 + + + + 4.5.0 - 4.5.1 + 4.5.2 diff --git a/external/dir.proj b/external/dir.proj index fccddc9f626d..cb86099dbf35 100644 --- a/external/dir.proj +++ b/external/dir.proj @@ -17,7 +17,7 @@ - + diff --git a/external/harvestPackages/harvestPackages.props b/external/harvestPackages/harvestPackages.props index 4b088b2258d0..38fa48fdd21a 100644 --- a/external/harvestPackages/harvestPackages.props +++ b/external/harvestPackages/harvestPackages.props @@ -1,4 +1,4 @@ - + @@ -62,10 +62,10 @@ 4.5.0 - 4.5.1 + 4.6.1 - 4.5.0 + 4.5.1 4.5.0 @@ -80,7 +80,7 @@ 4.5.0 - 4.5.0 + 4.5.1 4.5.0 @@ -89,7 +89,7 @@ 4.5.0 - 4.5.0 + 4.5.3 4.5.0 @@ -101,17 +101,14 @@ 4.5.0 - 4.5.0 + 4.5.4 - 4.5.1 + 4.5.3 0.1.0 - - 4.5.0 - 4.3.0 @@ -125,13 +122,13 @@ 1.6.0 - 4.5.0 + 4.5.1 4.5.0 - 4.5.1 + 4.5.2 4.3.0 @@ -146,10 +143,10 @@ 4.5.0 - 4.5.0 + 4.5.1 - 4.5.0 + 4.5.2 4.5.0 @@ -161,7 +158,7 @@ 4.5.0 - 4.5.0 + 4.5.1 4.5.0 @@ -170,7 +167,7 @@ 4.5.0 - 4.5.0 + 4.5.1 4.5.0 @@ -185,7 +182,7 @@ 4.9.0 - 4.5.1 + 4.5.2 4.5.0 diff --git a/external/netfx/netfx.depproj b/external/netfx/netfx.depproj index ccf87f90409c..8acf4c30625e 100644 --- a/external/netfx/netfx.depproj +++ b/external/netfx/netfx.depproj @@ -6,7 +6,7 @@ Reference NETStandard.Library.NETFramework 2.0.1-servicing-26011-01 - $(PackagesDir)$(NETStandardSupportPackageId.ToLower())\$(NETStandardSupportPackageVersion)\build + $(NuGetPackageRoot)$(NETStandardSupportPackageId.ToLower())\$(NETStandardSupportPackageVersion)\build true @@ -40,6 +40,9 @@ 4.5.2 + + 4.5.0 + $(NETStandardSupportPackageVersion) diff --git a/external/netstandard/netstandard.depproj b/external/netstandard/netstandard.depproj index 7e474bb52ef7..6c139d25e175 100644 --- a/external/netstandard/netstandard.depproj +++ b/external/netstandard/netstandard.depproj @@ -77,7 +77,7 @@ - <_NETStandard21RefFolder>$(PackagesDir)$(NETStandardLibraryPackageId.ToLower())\$(NETStandardLibraryPackageVersion)\build\netstandard2.1\ref + <_NETStandard21RefFolder>$(NuGetPackageRoot)$(NETStandardLibraryPackageId.ToLower())\$(NETStandardLibraryPackageVersion)\build\netstandard2.1\ref @@ -94,7 +94,7 @@ - <_NETStandardRefFolder>$(PackagesDir)$(NETStandardLibraryPackageId.ToLower())\$(NETStandardLibraryPackageVersion)\build\$(_NETStandardTFMFolder)\ref + <_NETStandardRefFolder>$(NuGetPackageRoot)$(NETStandardLibraryPackageId.ToLower())\$(NETStandardLibraryPackageVersion)\build\$(_NETStandardTFMFolder)\ref diff --git a/external/runtime/runtime.depproj b/external/runtime/runtime.depproj index 3a876a60aaf1..c7da29345fa8 100644 --- a/external/runtime/runtime.depproj +++ b/external/runtime/runtime.depproj @@ -2,10 +2,11 @@ $(PackageRID) $(NoWarn);NU1603;NU1605 + true + + false - - false Reference uap10.0 $(NoWarn);NU1701 @@ -30,7 +31,7 @@ - + $(MicrosoftNETCoreRuntimeCoreCLRPackageVersion) 2.1.0-b-uwp6-25707-02 @@ -45,19 +46,6 @@ - - - - - CoreCLRILFiles - $(NETCoreAppTestSharedFrameworkPath)il - - - CoreCLRCrossGenFiles - $(NETCoreAppTestSharedFrameworkPath)ni - - - @@ -87,86 +75,53 @@ - - $(PackagesDir)symbolpackages/ - https://dotnetfeed.blob.core.windows.net/dotnet-coreclr/assets/ - - - - - - <_CoreCLRSymbolPackagesToDownload Include="@(ReferenceCopyLocalPaths->'%(NuGetPackageId)')" Condition="$([System.String]::Copy('%(Identity)').EndsWith('System.Private.CoreLib.dll'))"> - $(DotNetAssetRootUrl)symbols/%(NuGetPackageId).%(NuGetPackageVersion).symbols.nupkg - %(NuGetPackageId).%(NuGetPackageVersion).symbols.nupkg.zip - $(SymbolPackagesDir)/%(NuGetPackageId).%(NuGetPackageVersion) - - - - - - - - - - - - - - - - - - <_CoreCLRSymbolFiles Include="%(_CoreCLRSymbolPackagesToDownload.UnzipDestinationDir)/runtimes/$(RuntimeIdentifier)/native/*.pdb" /> - <_CoreCLRSymbolFiles Include="%(_CoreCLRSymbolPackagesToDownload.UnzipDestinationDir)/runtimes/$(RuntimeIdentifier)/native/*.dbg" /> - - - - %(_CoreCLRSymbolPackagesToDownload.UnzipDestinationDir)/runtimes/$(RuntimeIdentifier)/native/ - - - - - - - - + $(CoreCLROverridePath)/PDB - true - - - - - + - <_ReferenceCopyLocalPathsToRemove Include="@(ReferenceCopyLocalPaths)" Condition="'@(CoreCLRFiles->'%(FileName)%(Extension)')' == '%(FileName)%(Extension)'" /> - - + + - + + - - - + + + <_CoreLibFile Include="@(ReferenceCopyLocalPaths)" Condition="'%(FileName)' == 'System.Private.CoreLib'" /> + + <_CoreLibFilePath>%(_CoreLibFile.FullPath) + <_CoreLibPackagePath>$(_CoreLibFilePath.SubString(0, $(_CoreLibFilePath.IndexOf('runtimes')))) + + + + + + + + + + + + + + + + + + diff --git a/external/test-runtime/XUnit.Runtime.depproj b/external/test-runtime/XUnit.Runtime.depproj index e795c082bc1c..4c69191a8ab8 100644 --- a/external/test-runtime/XUnit.Runtime.depproj +++ b/external/test-runtime/XUnit.Runtime.depproj @@ -34,10 +34,11 @@ - + + @@ -51,13 +52,14 @@ - + + @@ -98,7 +100,7 @@ AfterTargets="AfterResolveReferences"> - + @@ -127,7 +129,7 @@ AfterTargets="AfterResolveReferences"> - $(PackagesDir)$(MicrosoftDotNetUapTestToolsPackageName)\$(MicrosoftDotNetUapTestToolsPackageVersion)\Tools\$(ArchGroup) + $(NuGetPackageRoot)$(MicrosoftDotNetUapTestToolsPackageName)\$(MicrosoftDotNetUapTestToolsPackageVersion)\Tools\$(ArchGroup) $(UAPToolsFolder.Replace('/', '\')) @@ -151,36 +153,6 @@ - - - - - - - - - - TestILC - $(TestILCToolsPackageName).amd64ret - $(TestILCToolsPackageName).x86ret - $(TestILCToolsPackageName).armret - $(PackagesDir)$(TestILCToolsPackageName)\$(ProjectNTfsTestILCPackageVersion)\TestILC - - - - - - - - - - @@ -192,7 +164,7 @@ - <_microsoftNetTestSdkAssets Include="$(PackagesDir)$(MicrosoftNetTestSdkPackageName)\$(MicrosoftNETTestSdkPackageVersion)\build\$(TestSdkTFM)\*.*" /> + <_microsoftNetTestSdkAssets Include="$(NuGetPackageRoot)$(MicrosoftNetTestSdkPackageName)\$(MicrosoftNETTestSdkPackageVersion)\build\$(TestSdkTFM)\*.*" /> false $(MicrosoftNetTestSdkPackageName) @@ -201,7 +173,7 @@ + Text="Error: no assets for test sdk package were found under: $(NuGetPackageRoot)$(MicrosoftNetTestSdkPackageName)\$(MicrosoftNETTestSdkPackageVersion)\build\$(TestSdkTFM)\*.*" /> @@ -209,25 +181,25 @@ Condition="'$(TargetGroup)' == 'netcoreapp'" BeforeTargets="ResolveReferences"> - - - + + + - + false $(MicrosoftDotNetXUnitConsoleRunnerPackage) $(MicrosoftDotNetXUnitConsoleRunnerPackageVersion) - + false $(XUnitTestAdapterPackageId) $(XUnitPackageVersion) - + false $(TestPlatformHostPackageId) $(MicrosoftNETTestSdkPackageVersion) @@ -240,18 +212,18 @@ Condition="'$(TargetsUap)' == 'true'" BeforeTargets="ResolveReferences"> - - + + - + false $(XUnitTestAdapterPackageId) $(XUnitPackageVersion) - + false $(TestPlatformHostPackageId) $(MicrosoftNETTestSdkPackageVersion) @@ -264,18 +236,18 @@ Condition="'$(TargetsAot)' == 'true'" BeforeTargets="ResolveReferences"> - - + + - + false $(MicrosoftDotNetUapTestToolsPackageName) $(MicrosoftDotNetUapTestToolsPackageVersion) - + false xunit.runner.utility $(XUnitPackageVersion) @@ -288,19 +260,19 @@ Condition="'$(TargetGroup)' == 'netfx'" BeforeTargets="ResolveReferences"> - - + + - + false $(XUnitRunnerConsolePackageName) $(XUnitPackageVersion) - + false $(XUnitTestAdapterPackageId) $(XUnitPackageVersion) @@ -309,4 +281,20 @@ + + + + + + + false + $(MicrosoftDotNetRemoteExecutorPackage) + $(MicrosoftDotNetRemoteExecutorPackageVersion) + + + + + diff --git a/global.json b/global.json index 55ebddfb1aac..d71693b10a45 100644 --- a/global.json +++ b/global.json @@ -1,10 +1,11 @@ { "tools": { - "dotnet": "3.0.100-preview3-010431" + "dotnet": "3.0.100-preview6-011681" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "1.0.0-beta.19218.7", - "Microsoft.DotNet.Helix.Sdk": "2.0.0-beta.19257.7", - "Microsoft.NET.Sdk.IL": "3.0.0-preview5-27708-72" + "Microsoft.DotNet.Arcade.Sdk": "1.0.0-beta.19280.2", + "Microsoft.DotNet.Helix.Sdk": "2.0.0-beta.19280.2", + "FIX-85B6-MERGE-9C38-CONFLICT": "1.0.0", + "Microsoft.NET.Sdk.IL": "3.0.0-preview6.19280.2" } } diff --git a/pkg/Microsoft.NETCore.Platforms/runtime.compatibility.json b/pkg/Microsoft.NETCore.Platforms/runtime.compatibility.json index 64512cb82db9..1d45d566032f 100644 --- a/pkg/Microsoft.NETCore.Platforms/runtime.compatibility.json +++ b/pkg/Microsoft.NETCore.Platforms/runtime.compatibility.json @@ -303,6 +303,74 @@ "any", "base" ], + "debian.10": [ + "debian.10", + "debian", + "linux", + "unix", + "any", + "base" + ], + "debian.10-arm": [ + "debian.10-arm", + "debian.10", + "debian-arm", + "debian", + "linux-arm", + "linux", + "unix-arm", + "unix", + "any", + "base" + ], + "debian.10-arm64": [ + "debian.10-arm64", + "debian.10", + "debian-arm64", + "debian", + "linux-arm64", + "linux", + "unix-arm64", + "unix", + "any", + "base" + ], + "debian.10-armel": [ + "debian.10-armel", + "debian.10", + "debian-armel", + "debian", + "linux-armel", + "linux", + "unix-armel", + "unix", + "any", + "base" + ], + "debian.10-x64": [ + "debian.10-x64", + "debian.10", + "debian-x64", + "debian", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], + "debian.10-x86": [ + "debian.10-x86", + "debian.10", + "debian-x86", + "debian", + "linux-x86", + "linux", + "unix-x86", + "unix", + "any", + "base" + ], "debian.8": [ "debian.8", "debian", @@ -596,6 +664,46 @@ "any", "base" ], + "fedora.30": [ + "fedora.30", + "fedora", + "linux", + "unix", + "any", + "base" + ], + "fedora.30-x64": [ + "fedora.30-x64", + "fedora.30", + "fedora-x64", + "fedora", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], + "fedora.31": [ + "fedora.31", + "fedora", + "linux", + "unix", + "any", + "base" + ], + "fedora.31-x64": [ + "fedora.31-x64", + "fedora.31", + "fedora-x64", + "fedora", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], "freebsd": [ "freebsd", "unix", @@ -1086,6 +1194,67 @@ "any", "base" ], + "linuxmint.19.1": [ + "linuxmint.19.1", + "linuxmint.19", + "ubuntu.18.04", + "ubuntu", + "debian", + "linux", + "unix", + "any", + "base" + ], + "linuxmint.19.1-x64": [ + "linuxmint.19.1-x64", + "linuxmint.19.1", + "linuxmint.19-x64", + "linuxmint.19", + "ubuntu.18.04-x64", + "ubuntu.18.04", + "ubuntu-x64", + "ubuntu", + "debian-x64", + "debian", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], + "linuxmint.19.2": [ + "linuxmint.19.2", + "linuxmint.19.1", + "linuxmint.19", + "ubuntu.18.04", + "ubuntu", + "debian", + "linux", + "unix", + "any", + "base" + ], + "linuxmint.19.2-x64": [ + "linuxmint.19.2-x64", + "linuxmint.19.2", + "linuxmint.19.1-x64", + "linuxmint.19.1", + "linuxmint.19-x64", + "linuxmint.19", + "ubuntu.18.04-x64", + "ubuntu.18.04", + "ubuntu-x64", + "ubuntu", + "debian-x64", + "debian", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], "ol": [ "ol", "rhel", @@ -1482,6 +1651,64 @@ "any", "base" ], + "ol.8": [ + "ol.8", + "ol", + "rhel.8", + "rhel", + "linux", + "unix", + "any", + "base" + ], + "ol.8-x64": [ + "ol.8-x64", + "ol.8", + "ol-x64", + "rhel.8-x64", + "ol", + "rhel.8", + "rhel-x64", + "rhel", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], + "ol.8.0": [ + "ol.8.0", + "ol.8", + "rhel.8.0", + "ol", + "rhel.8", + "rhel", + "linux", + "unix", + "any", + "base" + ], + "ol.8.0-x64": [ + "ol.8.0-x64", + "ol.8.0", + "ol.8-x64", + "rhel.8.0-x64", + "ol.8", + "rhel.8.0", + "ol-x64", + "rhel.8-x64", + "ol", + "rhel.8", + "rhel-x64", + "rhel", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], "opensuse": [ "opensuse", "linux", @@ -1539,6 +1766,26 @@ "any", "base" ], + "opensuse.15.1": [ + "opensuse.15.1", + "opensuse", + "linux", + "unix", + "any", + "base" + ], + "opensuse.15.1-x64": [ + "opensuse.15.1-x64", + "opensuse.15.1", + "opensuse-x64", + "opensuse", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], "opensuse.42.1": [ "opensuse.42.1", "opensuse", @@ -2167,8 +2414,41 @@ "any", "base" ], + "sles.12.4": [ + "sles.12.4", + "sles.12.3", + "sles.12.2", + "sles.12.1", + "sles.12", + "sles", + "linux", + "unix", + "any", + "base" + ], + "sles.12.4-x64": [ + "sles.12.4-x64", + "sles.12.4", + "sles.12.3-x64", + "sles.12.3", + "sles.12.2-x64", + "sles.12.2", + "sles.12.1-x64", + "sles.12.1", + "sles.12-x64", + "sles.12", + "sles-x64", + "sles", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], "sles.15": [ "sles.15", + "sles.12.4", "sles.12.3", "sles.12.2", "sles.12.1", @@ -2182,6 +2462,46 @@ "sles.15-x64": [ "sles.15-x64", "sles.15", + "sles.12.4-x64", + "sles.12.4", + "sles.12.3-x64", + "sles.12.3", + "sles.12.2-x64", + "sles.12.2", + "sles.12.1-x64", + "sles.12.1", + "sles.12-x64", + "sles.12", + "sles-x64", + "sles", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], + "sles.15.1": [ + "sles.15.1", + "sles.15", + "sles.12.4", + "sles.12.3", + "sles.12.2", + "sles.12.1", + "sles.12", + "sles", + "linux", + "unix", + "any", + "base" + ], + "sles.15.1-x64": [ + "sles.15.1-x64", + "sles.15.1", + "sles.15-x64", + "sles.15", + "sles.12.4-x64", + "sles.12.4", "sles.12.3-x64", "sles.12.3", "sles.12.2-x64", @@ -2945,6 +3265,136 @@ "any", "base" ], + "ubuntu.19.04": [ + "ubuntu.19.04", + "ubuntu", + "debian", + "linux", + "unix", + "any", + "base" + ], + "ubuntu.19.04-arm": [ + "ubuntu.19.04-arm", + "ubuntu.19.04", + "ubuntu-arm", + "ubuntu", + "debian-arm", + "debian", + "linux-arm", + "linux", + "unix-arm", + "unix", + "any", + "base" + ], + "ubuntu.19.04-arm64": [ + "ubuntu.19.04-arm64", + "ubuntu.19.04", + "ubuntu-arm64", + "ubuntu", + "debian-arm64", + "debian", + "linux-arm64", + "linux", + "unix-arm64", + "unix", + "any", + "base" + ], + "ubuntu.19.04-x64": [ + "ubuntu.19.04-x64", + "ubuntu.19.04", + "ubuntu-x64", + "ubuntu", + "debian-x64", + "debian", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], + "ubuntu.19.04-x86": [ + "ubuntu.19.04-x86", + "ubuntu.19.04", + "ubuntu-x86", + "ubuntu", + "debian-x86", + "debian", + "linux-x86", + "linux", + "unix-x86", + "unix", + "any", + "base" + ], + "ubuntu.19.10": [ + "ubuntu.19.10", + "ubuntu", + "debian", + "linux", + "unix", + "any", + "base" + ], + "ubuntu.19.10-arm": [ + "ubuntu.19.10-arm", + "ubuntu.19.10", + "ubuntu-arm", + "ubuntu", + "debian-arm", + "debian", + "linux-arm", + "linux", + "unix-arm", + "unix", + "any", + "base" + ], + "ubuntu.19.10-arm64": [ + "ubuntu.19.10-arm64", + "ubuntu.19.10", + "ubuntu-arm64", + "ubuntu", + "debian-arm64", + "debian", + "linux-arm64", + "linux", + "unix-arm64", + "unix", + "any", + "base" + ], + "ubuntu.19.10-x64": [ + "ubuntu.19.10-x64", + "ubuntu.19.10", + "ubuntu-x64", + "ubuntu", + "debian-x64", + "debian", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], + "ubuntu.19.10-x86": [ + "ubuntu.19.10-x86", + "ubuntu.19.10", + "ubuntu-x86", + "ubuntu", + "debian-x86", + "debian", + "linux-x86", + "linux", + "unix-x86", + "unix", + "any", + "base" + ], "unix": [ "unix", "any", diff --git a/pkg/Microsoft.NETCore.Platforms/runtime.json b/pkg/Microsoft.NETCore.Platforms/runtime.json index f9ee87f9febf..af6347b76c6f 100644 --- a/pkg/Microsoft.NETCore.Platforms/runtime.json +++ b/pkg/Microsoft.NETCore.Platforms/runtime.json @@ -161,6 +161,41 @@ "linux-x86" ] }, + "debian.10": { + "#import": [ + "debian" + ] + }, + "debian.10-arm": { + "#import": [ + "debian.10", + "debian-arm" + ] + }, + "debian.10-arm64": { + "#import": [ + "debian.10", + "debian-arm64" + ] + }, + "debian.10-armel": { + "#import": [ + "debian.10", + "debian-armel" + ] + }, + "debian.10-x64": { + "#import": [ + "debian.10", + "debian-x64" + ] + }, + "debian.10-x86": { + "#import": [ + "debian.10", + "debian-x86" + ] + }, "debian.8": { "#import": [ "debian" @@ -319,6 +354,28 @@ "fedora-x64" ] }, + "fedora.30": { + "#import": [ + "fedora" + ] + }, + "fedora.30-x64": { + "#import": [ + "fedora.30", + "fedora-x64" + ] + }, + "fedora.31": { + "#import": [ + "fedora" + ] + }, + "fedora.31-x64": { + "#import": [ + "fedora.31", + "fedora-x64" + ] + }, "freebsd": { "#import": [ "unix" @@ -554,6 +611,28 @@ "ubuntu.18.04-x64" ] }, + "linuxmint.19.1": { + "#import": [ + "linuxmint.19" + ] + }, + "linuxmint.19.1-x64": { + "#import": [ + "linuxmint.19.1", + "linuxmint.19-x64" + ] + }, + "linuxmint.19.2": { + "#import": [ + "linuxmint.19.1" + ] + }, + "linuxmint.19.2-x64": { + "#import": [ + "linuxmint.19.2", + "linuxmint.19.1-x64" + ] + }, "ol": { "#import": [ "rhel" @@ -669,6 +748,32 @@ "rhel.7.6-x64" ] }, + "ol.8": { + "#import": [ + "ol", + "rhel.8" + ] + }, + "ol.8-x64": { + "#import": [ + "ol.8", + "ol-x64", + "rhel.8-x64" + ] + }, + "ol.8.0": { + "#import": [ + "ol.8", + "rhel.8.0" + ] + }, + "ol.8.0-x64": { + "#import": [ + "ol.8.0", + "ol.8-x64", + "rhel.8.0-x64" + ] + }, "opensuse": { "#import": [ "linux" @@ -702,6 +807,17 @@ "opensuse-x64" ] }, + "opensuse.15.1": { + "#import": [ + "opensuse" + ] + }, + "opensuse.15.1-x64": { + "#import": [ + "opensuse.15.1", + "opensuse-x64" + ] + }, "opensuse.42.1": { "#import": [ "opensuse" @@ -988,15 +1104,37 @@ "sles.12.2-x64" ] }, - "sles.15": { + "sles.12.4": { "#import": [ "sles.12.3" ] }, + "sles.12.4-x64": { + "#import": [ + "sles.12.4", + "sles.12.3-x64" + ] + }, + "sles.15": { + "#import": [ + "sles.12.4" + ] + }, "sles.15-x64": { "#import": [ "sles.15", - "sles.12.3-x64" + "sles.12.4-x64" + ] + }, + "sles.15.1": { + "#import": [ + "sles.15" + ] + }, + "sles.15.1-x64": { + "#import": [ + "sles.15.1", + "sles.15-x64" ] }, "tizen": { @@ -1345,6 +1483,64 @@ "ubuntu-x86" ] }, + "ubuntu.19.04": { + "#import": [ + "ubuntu" + ] + }, + "ubuntu.19.04-arm": { + "#import": [ + "ubuntu.19.04", + "ubuntu-arm" + ] + }, + "ubuntu.19.04-arm64": { + "#import": [ + "ubuntu.19.04", + "ubuntu-arm64" + ] + }, + "ubuntu.19.04-x64": { + "#import": [ + "ubuntu.19.04", + "ubuntu-x64" + ] + }, + "ubuntu.19.04-x86": { + "#import": [ + "ubuntu.19.04", + "ubuntu-x86" + ] + }, + "ubuntu.19.10": { + "#import": [ + "ubuntu" + ] + }, + "ubuntu.19.10-arm": { + "#import": [ + "ubuntu.19.10", + "ubuntu-arm" + ] + }, + "ubuntu.19.10-arm64": { + "#import": [ + "ubuntu.19.10", + "ubuntu-arm64" + ] + }, + "ubuntu.19.10-x64": { + "#import": [ + "ubuntu.19.10", + "ubuntu-x64" + ] + }, + "ubuntu.19.10-x86": { + "#import": [ + "ubuntu.19.10", + "ubuntu-x86" + ] + }, "unix": { "#import": [ "any" diff --git a/pkg/Microsoft.NETCore.Platforms/runtimeGroups.props b/pkg/Microsoft.NETCore.Platforms/runtimeGroups.props index a819d57ddc61..55299c20432a 100644 --- a/pkg/Microsoft.NETCore.Platforms/runtimeGroups.props +++ b/pkg/Microsoft.NETCore.Platforms/runtimeGroups.props @@ -35,14 +35,14 @@ linux x64;x86;arm;armel;arm64 - 8;9 + 8;9;10 false linux x64 - 23;24;25;26;27;28;29 + 23;24;25;26;27;28;29;30;31 false @@ -65,7 +65,7 @@ ubuntu.18.04 x64 - + 1;2 @@ -74,12 +74,18 @@ 7;7.0;7.1;7.2;7.3;7.4;7.5;7.6 true + + rhel + x64 + 8;8.0 + true + linux x64 - 13.2;15.0;42.1;42.2;42.3 + 13.2;15.0;15.1;42.1;42.2;42.3 false @@ -107,7 +113,6 @@ x64 7;7.0;7.1;7.2;7.3;7.4;7.5;7.6 - linux x64 @@ -117,7 +122,7 @@ linux x64 - 12;12.1;12.2;12.3;15 + 12;12.1;12.2;12.3;12.4;15;15.1 @@ -135,7 +140,7 @@ debian x64;x86;arm;arm64 - 16.04;16.10;17.04;17.10;18.04;18.10 + 16.04;16.10;17.04;17.10;18.04;18.10;19.04;19.10 false diff --git a/pkg/Microsoft.NETCore.Targets/Microsoft.NETCore.Targets.pkgproj b/pkg/Microsoft.NETCore.Targets/Microsoft.NETCore.Targets.pkgproj index d57412478ead..2c48d5fbe229 100644 --- a/pkg/Microsoft.NETCore.Targets/Microsoft.NETCore.Targets.pkgproj +++ b/pkg/Microsoft.NETCore.Targets/Microsoft.NETCore.Targets.pkgproj @@ -11,7 +11,6 @@ lib/netstandard1.0 - diff --git a/pkg/Microsoft.NETCore.Targets/runtime.json b/pkg/Microsoft.NETCore.Targets/runtime.json deleted file mode 100644 index 925514c3611f..000000000000 --- a/pkg/Microsoft.NETCore.Targets/runtime.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "supports": { - "uwp.10.0.app": { - "uap10.0": [ - "win10-x86", - "win10-x86-aot", - "win10-x64", - "win10-x64-aot", - "win10-arm", - "win10-arm-aot" - ] - }, - "net45.app": { - "net45": [ - "", - "win-x86", - "win-x64" - ] - }, - "net451.app": { - "net451": [ - "", - "win-x86", - "win-x64" - ] - }, - "net452.app": { - "net452": [ - "", - "win-x86", - "win-x64" - ] - }, - "net46.app": { - "net46": [ - "", - "win-x86", - "win-x64" - ] - }, - "net461.app": { - "net461": [ - "", - "win-x86", - "win-x64" - ] - }, - "net462.app": { - "net462": [ - "", - "win-x86", - "win-x64" - ] - }, - "netcoreapp1.0.app": { - "netcoreapp1.0": [ - "win7-x86", - "win7-x64", - "osx.10.11-x64", - "centos.7-x64", - "debian.8-x64", - "linuxmint.17-x64", - "opensuse.13.2-x64", - "rhel.7.2-x64", - "ubuntu.14.04-x64", - "ubuntu.16.04-x64" - ] - }, - "win8.app": { - "win8": "" - }, - "win81.app": { - "win81": "" - }, - "wp8.app": { - "wp8": "" - }, - "wp81.app": { - "wp81": "" - }, - "wpa81.app": { - "wpa81": "" - }, - "dnxcore50.app": { - "dnxcore50": [ - "win7-x86", - "win7-x64" - ] - } - } - } - diff --git a/pkg/Microsoft.Private.CoreFx.OOB/Microsoft.Private.CoreFx.OOB.builds b/pkg/Microsoft.Private.CoreFx.OOB/Microsoft.Private.CoreFx.OOB.builds new file mode 100644 index 000000000000..17a7f1689029 --- /dev/null +++ b/pkg/Microsoft.Private.CoreFx.OOB/Microsoft.Private.CoreFx.OOB.builds @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/pkg/Microsoft.Private.CoreFx.OOB/Microsoft.Private.CoreFx.OOB.pkgproj b/pkg/Microsoft.Private.CoreFx.OOB/Microsoft.Private.CoreFx.OOB.pkgproj new file mode 100644 index 000000000000..def37549519f --- /dev/null +++ b/pkg/Microsoft.Private.CoreFx.OOB/Microsoft.Private.CoreFx.OOB.pkgproj @@ -0,0 +1,34 @@ + + + + + <_PreReleasePackageVersion>$(PackageVersion) + + false + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pkg/Microsoft.Private.PackageBaseline/Microsoft.Private.PackageBaseline.pkgproj b/pkg/Microsoft.Private.PackageBaseline/Microsoft.Private.PackageBaseline.pkgproj index b9bd433bee7a..52b3b657ca59 100644 --- a/pkg/Microsoft.Private.PackageBaseline/Microsoft.Private.PackageBaseline.pkgproj +++ b/pkg/Microsoft.Private.PackageBaseline/Microsoft.Private.PackageBaseline.pkgproj @@ -30,10 +30,10 @@ $(UAPvNextTFM) - + netstandard2.0 - + net461 diff --git a/pkg/Microsoft.Private.PackageBaseline/packageIndex.json b/pkg/Microsoft.Private.PackageBaseline/packageIndex.json index e1ab4eb8d7e0..18f5f8a3eb15 100644 --- a/pkg/Microsoft.Private.PackageBaseline/packageIndex.json +++ b/pkg/Microsoft.Private.PackageBaseline/packageIndex.json @@ -27,6 +27,18 @@ "net45": "4.0.0.0" } }, + "Microsoft.Bcl.AsyncInterfaces": { + "InboxOn": {}, + "AssemblyVersionInPackageVersion": { + "1.0.0.0": "1.0.0" + } + }, + "Microsoft.Bcl.HashCode": { + "InboxOn": {}, + "AssemblyVersionInPackageVersion": { + "1.0.0.0": "1.0.0" + } + }, "Microsoft.Bcl.Json.Sources": { "InboxOn": {} }, @@ -68,7 +80,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "netcoreapp2.0": "4.0.3.0", "netcoreapp2.1": "4.0.4.0", @@ -101,7 +113,7 @@ "4.0.1.0": "4.0.1", "4.0.2.0": "4.3.0", "4.0.3.0": "4.4.0", - "4.0.4.0": "4.6.0" + "4.0.4.0": "4.5.0" } }, "Microsoft.Devices.Sensors": { @@ -139,9 +151,14 @@ "1.0.2", "1.1.0", "2.0.0", - "2.1.0" - ], - "BaselineVersion": "2.0.0", + "2.1.0", + "2.1.1", + "2.1.2", + "2.1.3", + "2.1.4", + "2.2.0" + ], + "BaselineVersion": "3.0.0", "InboxOn": {} }, "Microsoft.NETCore.Targets": { @@ -153,7 +170,7 @@ "2.0.0", "2.1.0" ], - "BaselineVersion": "2.0.0", + "BaselineVersion": "3.0.0", "InboxOn": {} }, "Microsoft.Phone": { @@ -189,6 +206,9 @@ "Microsoft.Private.CoreFx.NETCoreApp": { "InboxOn": {} }, + "Microsoft.Private.CoreFx.OOB": { + "InboxOn": {} + }, "Microsoft.Private.PackageBaseline": { "InboxOn": {} }, @@ -219,7 +239,7 @@ "10.0.1.0": "10.0.1", "10.0.2.0": "10.1.0", "10.0.3.0": "10.2.0", - "10.0.4.0": "10.4.0" + "10.0.4.0": "10.3.0" } }, "Microsoft.VisualBasic.Compatibility": { @@ -281,7 +301,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.0.0", @@ -298,7 +318,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.0.0", @@ -312,7 +332,7 @@ "StableVersions": [ "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.5.0", @@ -321,13 +341,16 @@ }, "Microsoft.Windows.Compatibility": { "StableVersions": [ - "2.0.0" + "2.0.0", + "2.0.1", + "2.1.0" ], "InboxOn": {} }, "Microsoft.Windows.Compatibility.Shims": { "StableVersions": [ - "2.0.0" + "2.0.0", + "2.0.1" ], "InboxOn": {} }, @@ -427,6 +450,7 @@ "netcoreapp3.0": "2.1.0.0", "net461": "2.0.0.0", "netstandard2.0": "2.0.0.0", + "netstandard2.1": "2.1.0.0", "uap10.0.16299": "2.0.0.0", "uap10.0.16300": "2.1.0.0" } @@ -496,7 +520,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {} }, "runtime.native.System.IO.Ports": { @@ -645,7 +669,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.4.0", @@ -740,7 +764,7 @@ "1.4.0", "1.5.0" ], - "BaselineVersion": "1.5.0", + "BaselineVersion": "1.6.0", "InboxOn": { "netcoreapp2.0": "1.2.2.0", "netcoreapp2.1": "1.2.3.0", @@ -858,7 +882,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "netcoreapp2.0": "4.2.0.0", "netcoreapp2.1": "4.2.1.0", @@ -891,7 +915,7 @@ "StableVersions": [ "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "net45": "4.0.0.0", "monoandroid10": "Any", @@ -903,7 +927,7 @@ "xamarinwatchos10": "Any" }, "AssemblyVersionInPackageVersion": { - "4.0.0.0": "4.6.0" + "4.0.0.0": "4.5.0" } }, "System.ComponentModel.Composition.Registration": { @@ -1031,7 +1055,7 @@ "1.1.0", "1.2.0" ], - "BaselineVersion": "1.2.0", + "BaselineVersion": "1.3.0", "InboxOn": {} }, "System.Composition.AttributedModel": { @@ -1040,7 +1064,7 @@ "1.1.0", "1.2.0" ], - "BaselineVersion": "1.2.0", + "BaselineVersion": "1.3.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "1.0.31.0": "1.0.31", @@ -1055,7 +1079,7 @@ "1.1.0", "1.2.0" ], - "BaselineVersion": "1.2.0", + "BaselineVersion": "1.3.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "1.0.31.0": "1.0.31", @@ -1070,7 +1094,7 @@ "1.1.0", "1.2.0" ], - "BaselineVersion": "1.2.0", + "BaselineVersion": "1.3.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "1.0.31.0": "1.0.31", @@ -1085,7 +1109,7 @@ "1.1.0", "1.2.0" ], - "BaselineVersion": "1.2.0", + "BaselineVersion": "1.3.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "1.0.31.0": "1.0.31", @@ -1100,7 +1124,7 @@ "1.1.0", "1.2.0" ], - "BaselineVersion": "1.2.0", + "BaselineVersion": "1.3.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "1.0.31.0": "1.0.31", @@ -1121,7 +1145,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.4.0", @@ -1232,12 +1256,12 @@ ], "BaselineVersion": "4.5.0", "InboxOn": { - "net45": "4.0.0.0", "netcoreapp3.0": "4.0.0.0", + "net45": "4.0.0.0", "uap10.0.16300": "4.0.0.0" }, "AssemblyVersionInPackageVersion": { - "4.0.0.0": "4.6.0" + "4.0.0.0": "4.5.0" } }, "System.Data.Entity": { @@ -1260,13 +1284,19 @@ "StableVersions": [ "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.5.0", "4.0.1.0": "4.6.0" } }, + "System.Data.OleDb": { + "InboxOn": {}, + "AssemblyVersionInPackageVersion": { + "4.0.0.0": "4.6.0" + } + }, "System.Data.OracleClient": { "InboxOn": { "net45": "4.0.0.0" @@ -1298,9 +1328,12 @@ "4.1.0", "4.3.0", "4.4.0", - "4.5.1" + "4.5.1", + "4.5.0", + "4.6.0", + "4.6.1" ], - "BaselineVersion": "4.5.1", + "BaselineVersion": "4.7.0", "InboxOn": { "net461": "4.1.0.0", "monoandroid10": "Any", @@ -1319,6 +1352,7 @@ "4.2.0.0": "4.4.0", "4.4.0.0": "4.5.0", "4.5.0.0": "4.6.0", + "4.5.0.1": "4.6.1", "4.6.0.0": "4.7.0" } }, @@ -1430,12 +1464,13 @@ "4.0.0", "4.3.0", "4.4.1", - "4.5.0" + "4.5.0", + "4.5.1" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "netcoreapp2.0": "4.0.2.1", - "netcoreapp2.1": "4.0.3.0", + "netcoreapp2.1": "4.0.3.1", "netcoreapp3.0": "4.0.4.0" }, "AssemblyVersionInPackageVersion": { @@ -1444,6 +1479,7 @@ "4.0.2.0": "4.4.0", "4.0.2.1": "4.4.1", "4.0.3.0": "4.5.0", + "4.0.3.1": "4.5.1", "4.0.4.0": "4.6.0" } }, @@ -1451,6 +1487,7 @@ "StableVersions": [ "4.5.0" ], + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.5.0", @@ -1485,7 +1522,7 @@ "StableVersions": [ "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "monoandroid10": "Any", "monotouch10": "Any", @@ -1695,36 +1732,36 @@ "StableVersions": [ "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "net45": "4.0.0.0" }, "AssemblyVersionInPackageVersion": { - "4.0.0.0": "4.6.0" + "4.0.0.0": "4.5.0" } }, "System.DirectoryServices.AccountManagement": { "StableVersions": [ "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "net45": "4.0.0.0" }, "AssemblyVersionInPackageVersion": { - "4.0.0.0": "4.6.0" + "4.0.0.0": "4.5.0" } }, "System.DirectoryServices.Protocols": { "StableVersions": [ "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "net45": "4.0.0.0" }, "AssemblyVersionInPackageVersion": { - "4.0.0.0": "4.6.0" + "4.0.0.0": "4.5.0" } }, "System.Drawing": { @@ -1737,9 +1774,10 @@ }, "System.Drawing.Common": { "StableVersions": [ - "4.5.0" + "4.5.0", + "4.5.1" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "monoandroid10": "Any", "monotouch10": "Any", @@ -1750,6 +1788,7 @@ }, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.5.0", + "4.0.0.1": "4.5.1", "4.0.1.0": "4.6.0" } }, @@ -2109,7 +2148,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.0.0", @@ -2255,7 +2294,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.0.0", @@ -2267,12 +2306,16 @@ }, "System.IO.Pipelines": { "StableVersions": [ - "4.5.0" + "4.5.0", + "4.5.1", + "4.5.2", + "4.5.3" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.5.0", + "4.0.0.1": "4.5.2", "4.0.1.0": "4.6.0" } }, @@ -2316,14 +2359,14 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "uap10.0.16299": "4.0.1.0", "uap10.0.16300": "4.0.2.0" }, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.4.0", - "4.0.1.0": "4.6.0", + "4.0.1.0": "4.5.0", "4.0.2.0": "4.6.0" } }, @@ -2358,7 +2401,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "monoandroid10": "Any", "monotouch10": "Any", @@ -2496,7 +2539,7 @@ "4.0.1", "4.3.0" ], - "BaselineVersion": "4.3.0", + "BaselineVersion": "4.6.0", "InboxOn": { "netcoreapp2.0": "4.0.3.0", "net45": "4.0.0.0", @@ -2533,12 +2576,12 @@ "StableVersions": [ "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "net45": "4.0.0.0" }, "AssemblyVersionInPackageVersion": { - "4.0.0.0": "4.6.0" + "4.0.0.0": "4.5.0" } }, "System.Management.Instrumentation": { @@ -2549,8 +2592,11 @@ "System.Memory": { "StableVersions": [ "4.5.0", - "4.5.1" + "4.5.1", + "4.5.2", + "4.5.3" ], + "BaselineVersion": "4.5.3", "InboxOn": { "netcoreapp2.1": "4.1.0.0", "netcoreapp3.0": "4.2.0.0", @@ -2563,7 +2609,9 @@ "xamarinwatchos10": "Any" }, "AssemblyVersionInPackageVersion": { + "4.0.0.0": "4.4.0", "4.0.1.0": "4.5.0", + "4.0.1.1": "4.5.3", "4.1.0.0": "4.6.0" } }, @@ -2694,16 +2742,24 @@ "4.0.0", "4.0.1", "4.3.0", + "4.3.3", "4.4.0", - "4.5.0" + "4.5.0", + "4.5.1", + "4.5.2", + "4.5.3", + "4.5.4" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.0.0", "4.0.1.0": "4.3.0", + "4.0.1.3": "4.3.3", "4.0.2.0": "4.4.0", "4.0.3.0": "4.5.0", + "4.0.3.1": "4.5.1", + "4.0.3.2": "4.5.3", "4.0.4.0": "4.6.0" } }, @@ -3077,12 +3133,17 @@ }, "System.Net.WebSockets.WebSocketProtocol": { "StableVersions": [ - "4.5.1" + "4.5.1", + "4.5.0", + "4.5.2", + "4.5.3" ], - "BaselineVersion": "4.5.1", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.5.0", + "4.0.0.1": "4.5.2", + "4.0.0.2": "4.5.3", "4.0.1.0": "4.6.0" } }, @@ -3111,6 +3172,7 @@ "StableVersions": [ "0.1.0" ], + "BaselineVersion": "0.2.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "0.1.0.0": "0.1.0", @@ -3148,8 +3210,7 @@ "4.1.1.0": "4.1.1", "4.1.2.0": "4.3.0", "4.1.3.0": "4.4.0", - "4.1.4.0": "4.5.0", - "4.1.5.0": "4.6.0" + "4.1.4.0": "4.5.0" } }, "System.Numerics.Vectors.WindowsRuntime": { @@ -3298,11 +3359,12 @@ "4.0.0", "4.3.0" ], - "BaselineVersion": "4.3.0", + "BaselineVersion": "4.6.0", "InboxOn": { "net45": "4.0.0.0", "portable46-net451+win81": "4.0.0.0", "portable45-net45+win8": "4.0.0.0", + "uap10.0.16299": "4.0.3.0", "win8": "4.0.0.0" }, "AssemblyVersionInPackageVersion": { @@ -3318,9 +3380,10 @@ "4.0.1", "4.3.0", "4.4.0", - "4.5.1" + "4.5.1", + "4.5.0" ], - "BaselineVersion": "4.5.1", + "BaselineVersion": "4.6.0", "InboxOn": { "netcoreapp2.0": "4.0.3.0", "netcoreapp2.1": "4.0.4.0", @@ -3349,11 +3412,12 @@ "4.0.1", "4.3.0" ], - "BaselineVersion": "4.3.0", + "BaselineVersion": "4.6.0", "InboxOn": { "netcoreapp2.0": "4.1.0.0", "netcoreapp2.1": "4.1.1.0", "net45": "4.0.0.0", + "netstandard2.1": "4.0.0.0", "monoandroid10": "Any", "xamarinmac20": "Any" }, @@ -3376,6 +3440,7 @@ "netcoreapp2.0": "4.0.3.0", "net45": "4.0.0.0", "portable45-net45+wp8": "4.0.0.0", + "netstandard2.1": "4.0.0.0", "monoandroid10": "Any", "monotouch10": "Any", "wp8": "4.0.0.0", @@ -3402,6 +3467,7 @@ "netcoreapp2.0": "4.0.3.0", "net45": "4.0.0.0", "portable45-net45+wp8": "4.0.0.0", + "netstandard2.1": "4.0.0.0", "monoandroid10": "Any", "monotouch10": "Any", "wp8": "4.0.0.0", @@ -3467,7 +3533,7 @@ "1.5.0", "1.6.0" ], - "BaselineVersion": "1.6.0", + "BaselineVersion": "1.7.0", "InboxOn": { "netcoreapp2.0": "1.4.2.0", "netcoreapp2.1": "1.4.3.0", @@ -3538,9 +3604,10 @@ "4.1.0", "4.3.0", "4.4.0", - "4.5.0" + "4.5.0", + "4.5.1" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "netcoreapp2.0": "4.1.2.0", "netcoreapp2.1": "4.1.3.0", @@ -3563,6 +3630,12 @@ "4.1.4.0": "4.6.0" } }, + "System.Resources.Extensions": { + "InboxOn": {}, + "AssemblyVersionInPackageVersion": { + "4.0.0.0": "4.6.0" + } + }, "System.Resources.Reader": { "StableVersions": [ "4.0.0", @@ -3701,7 +3774,7 @@ "StableVersions": [ "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "net45": "4.0.0.0", "monoandroid10": "Any", @@ -3712,23 +3785,25 @@ "xamarinwatchos10": "Any" }, "AssemblyVersionInPackageVersion": { - "4.0.0.0": "4.6.0" + "4.0.0.0": "4.5.0" } }, "System.Runtime.CompilerServices.Unsafe": { "StableVersions": [ "4.4.0", "4.5.0", - "4.5.1" + "4.5.1", + "4.5.2" ], - "BaselineVersion": "4.5.1", + "BaselineVersion": "4.6.0", "InboxOn": { - "uap10.0.16300": "4.0.5.0", - "netcoreapp3.0": "4.0.5.0" + "netcoreapp3.0": "4.0.5.0", + "uap10.0.16300": "4.0.5.0" }, "AssemblyVersionInPackageVersion": { "4.0.3.0": "4.4.0", "4.0.4.0": "4.5.0", + "4.0.4.1": "4.5.2", "4.0.5.0": "4.6.0" } }, @@ -3901,7 +3976,7 @@ "4.0.1", "4.3.0" ], - "BaselineVersion": "4.3.0", + "BaselineVersion": "4.6.0", "InboxOn": { "netcoreapp2.0": "4.0.3.0", "net45": "4.0.0.0", @@ -4223,7 +4298,7 @@ "4.0.0", "4.3.0" ], - "BaselineVersion": "4.3.0", + "BaselineVersion": "4.6.0", "InboxOn": { "net45": "4.0.0.0", "portable46-win81+wpa81": "4.0.0.0", @@ -4253,7 +4328,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "uap10.0.16299": "4.1.1.0" }, @@ -4261,7 +4336,7 @@ "4.0.0.0": "4.0.0", "4.0.1.0": "4.3.0", "4.1.0.0": "4.4.0", - "4.1.1.0": "4.6.0", + "4.1.1.0": "4.5.0", "4.1.2.0": "4.6.0" } }, @@ -4324,7 +4399,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "monoandroid10": "Any", "monotouch10": "Any", @@ -4398,15 +4473,17 @@ "4.0.0", "4.3.0", "4.4.0", - "4.5.0" + "4.5.0", + "4.5.1" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.0.0", "4.0.1.0": "4.3.0", "4.1.0.0": "4.4.0", "4.1.1.0": "4.5.0", + "4.1.1.1": "4.5.1", "4.1.2.0": "4.6.0" } }, @@ -4415,15 +4492,19 @@ "4.0.0", "4.3.0", "4.4.0", - "4.5.0" + "4.5.0", + "4.5.1", + "4.5.2" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.0.0", "4.0.1.0": "4.3.0", "4.0.2.0": "4.4.0", "4.0.3.0": "4.5.0", + "4.0.3.1": "4.5.1", + "4.0.3.2": "4.5.2", "4.0.4.0": "4.6.0", "4.1.0.0": "4.6.0" } @@ -4459,7 +4540,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "monoandroid10": "Any", "monotouch10": "Any", @@ -4506,7 +4587,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.4.0", @@ -4519,7 +4600,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.4.0", @@ -4572,9 +4653,10 @@ "4.0.0", "4.3.0", "4.4.0", - "4.5.0" + "4.5.0", + "4.5.1" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "uap10.0.16299": "4.1.1.0" }, @@ -4582,7 +4664,8 @@ "4.0.0.0": "4.0.0", "4.0.1.0": "4.3.0", "4.1.0.0": "4.4.0", - "4.1.1.0": "4.6.0", + "4.1.1.0": "4.5.0", + "4.1.1.1": "4.5.1", "4.1.2.0": "4.6.0" } }, @@ -4750,7 +4833,7 @@ "StableVersions": [ "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.5.0", @@ -4798,7 +4881,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.1.0.0": "4.1.0", @@ -4862,9 +4945,10 @@ "4.0.1", "4.3.0", "4.4.0", - "4.5.0" + "4.5.0", + "4.5.1" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": { "monoandroid10": "Any", "monotouch10": "Any", @@ -4934,8 +5018,10 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", - "InboxOn": {}, + "BaselineVersion": "4.6.0", + "InboxOn": { + "netcoreapp3.0": "4.0.4.0" + }, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.0.0", "4.0.1.0": "4.3.0", @@ -5047,7 +5133,7 @@ "4.4.0", "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.0.0", @@ -5061,7 +5147,7 @@ "StableVersions": [ "4.5.0" ], - "BaselineVersion": "4.5.0", + "BaselineVersion": "4.6.0", "InboxOn": {}, "AssemblyVersionInPackageVersion": { "4.0.0.0": "4.5.0", @@ -5139,7 +5225,7 @@ "4.8.0", "4.9.0" ], - "BaselineVersion": "4.9.0", + "BaselineVersion": "4.10.0", "InboxOn": { "netcoreapp2.0": "4.6.2.0", "netcoreapp2.1": "4.6.3.0", @@ -5161,9 +5247,11 @@ "4.0.0", "4.3.0", "4.4.0", - "4.5.1" + "4.5.1", + "4.5.2", + "4.5.0" ], - "BaselineVersion": "4.5.1", + "BaselineVersion": "4.5.2", "InboxOn": { "netcoreapp2.0": "4.1.1.0", "netcoreapp2.1": "4.3.0.0", @@ -5939,4 +6027,4 @@ "System.Xml.XDocument" ] } -} +} \ No newline at end of file diff --git a/pkg/Microsoft.Windows.Compatibility/Microsoft.Windows.Compatibility.pkgproj b/pkg/Microsoft.Windows.Compatibility/Microsoft.Windows.Compatibility.pkgproj index 52fb8f3764fd..1c9ce5a57bff 100644 --- a/pkg/Microsoft.Windows.Compatibility/Microsoft.Windows.Compatibility.pkgproj +++ b/pkg/Microsoft.Windows.Compatibility/Microsoft.Windows.Compatibility.pkgproj @@ -24,6 +24,7 @@ + 4.7.0 diff --git a/pkg/baseline/packageBaseline.1.1.json b/pkg/baseline/packageBaseline.1.1.json index deadd99eaa2e..c1b6c58d7aa1 100644 --- a/pkg/baseline/packageBaseline.1.1.json +++ b/pkg/baseline/packageBaseline.1.1.json @@ -446,4 +446,4 @@ } }, "ModulesToPackages": {} -} \ No newline at end of file +} diff --git a/pkg/descriptions.json b/pkg/descriptions.json index eb6700439880..6367b981e4b7 100644 --- a/pkg/descriptions.json +++ b/pkg/descriptions.json @@ -30,6 +30,13 @@ "Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags" ] }, + { + "Name": "Microsoft.Bcl.HashCode", + "Description": "Provides the HashCode type for .NET Standard 2.0. This package is not required starting with .NET Standard 2.1 and .NET Core 3.0.", + "CommonTypes": [ + "System.HashCode" + ] + }, { "Name": "Microsoft.Diagnostics.Tracing.EventSource.Redist", "Description": "This package includes the class Microsoft.Diagnostics.Tracing.EventSource which enables firing ETW events from managed code. This is the \"runtime\" or \"redist\" EventSource package and should be referenced directly only by other NuGet packages that need the EventSource functionality. Application developers that need this functionality should instead reference the Microsoft.Diagnostics.Tracing.EventSource NuGet package which provides an enhanced developer experience. @@ -148,6 +155,11 @@ "Description": "Package used to represent the portions of NETCoreApp that come from CoreFx.", "CommonTypes": [] }, + { + "Name": "Microsoft.Private.CoreFx.OOB", + "Description": "Package used to represent out-of-band packages that are not included in NetCoreApp.", + "CommonTypes": [] + }, { "Name": "Microsoft.Private.CoreFx.UAP", "Description": "Package used to represent the portions of UAP that come from CoreFx.", @@ -540,6 +552,20 @@ "System.Data.Odbc.OdbcTransaction" ] }, + { + "Name": "System.Data.OleDb", + "Description": "Provides a collection of classes for OLEDB.", + "CommonTypes": [ + "System.Data.OleDb.OleDbCommand", + "System.Data.OleDb.OleDbCommandBuilder", + "System.Data.OleDb.OleDbConnection", + "System.Data.OleDb.OleDbDataAdapter", + "System.Data.OleDb.OleDbDataReader", + "System.Data.OleDb.OleDbParameter", + "System.Data.OleDb.OleDbParameterCollection", + "System.Data.OleDb.OleDbTransaction" + ] + }, { "Name": "System.Data.SqlClient", "Description": "Provides the data provider for SQL Server. These classes provide access to versions of SQL Server and encapsulate database-specific protocols, including tabular data stream (TDS)", @@ -1042,6 +1068,15 @@ "System.Buffers.Text.Utf8Formatter" ] }, + { + "Name": "Microsoft.Bcl.AsyncInterfaces", + "Description": "Provides the IAsyncEnumerable and IAsyncDisposable interfaces and helper types for .NET Standard 2.0. This package is not required starting with .NET Standard 2.1 and .NET Core 3.0.", + "CommonTypes": [ + "System.IAsyncDisposable", + "System.Collections.Generic.IAsyncEnumerable", + "System.Collections.Generic.IAsyncEnumerator" + ] + }, { "Name": "System.Net.Http", "Description": "Provides a programming interface for modern HTTP applications, including HTTP client components that allow applications to consume web services over HTTP and HTTP components that can be used by both clients and servers for parsing HTTP headers.", @@ -1245,21 +1280,6 @@ "System.Numerics.Tensors.SparseTensor" ] }, - { - "Name": "System.Numerics.Vectors", - "Description": "Provides hardware-accelerated numeric types, suitable for high-performance processing and graphics applications.", - "CommonTypes": [ - "System.Numerics.Matrix3x2", - "System.Numerics.Matrix4x4", - "System.Numerics.Plane", - "System.Numerics.Quaternion", - "System.Numerics.Vector2", - "System.Numerics.Vector3", - "System.Numerics.Vector4", - "System.Numerics.Vector", - "System.Numerics.Vector" - ] - }, { "Name": "System.Numerics.Vectors.WindowsRuntime", "Description": "Provides extension methods for converting between System.Numerics.Vector2 and Windows.Foundation.Point and Size.", @@ -1428,6 +1448,14 @@ "System.Resources.SatelliteContractVersionAttribute", "System.Resources.MissingManifestResourceException" ] + }, + { + "Name": "System.Resources.Extensions", + "Description": "Provides classes which read and write resources in a format that supports non-primitive objects.", + "CommonTypes": [ + "System.Resources.Extensions.DeserializingResourceReader", + "System.Resources.Extensions.PreserializedResourceWriter" + ] }, { "Name": "System.Resources.Reader", diff --git a/pkg/frameworkPackage.targets b/pkg/frameworkPackage.targets index 1c0abf101f06..c91d1ebe3132 100644 --- a/pkg/frameworkPackage.targets +++ b/pkg/frameworkPackage.targets @@ -5,7 +5,7 @@ true 2.0 - $(PackagesDir)$(NETStandardLibraryPackageId.ToLower())\$(NETStandardLibraryPackageVersion)\build\netstandard$(NETStandardVersion)\ref + $(NuGetPackageRoot)$(NETStandardLibraryPackageId.ToLower())\$(NETStandardLibraryPackageVersion)\build\netstandard$(NETStandardVersion)\ref true true diff --git a/pkg/test/frameworkSettings/net/settings.targets b/pkg/test/frameworkSettings/net/settings.targets index 25b7f5936bc7..b7ee4126aa5d 100644 --- a/pkg/test/frameworkSettings/net/settings.targets +++ b/pkg/test/frameworkSettings/net/settings.targets @@ -8,7 +8,7 @@ - + diff --git a/pkg/test/frameworkSettings/netcoreapp3.0/settings.targets b/pkg/test/frameworkSettings/netcoreapp3.0/settings.targets index afde20c57942..4397153c29fa 100644 --- a/pkg/test/frameworkSettings/netcoreapp3.0/settings.targets +++ b/pkg/test/frameworkSettings/netcoreapp3.0/settings.targets @@ -15,11 +15,4 @@ - - - - - diff --git a/pkg/test/packageSettings/System.Diagnostics.DiagnosticSource/workaroundMissingSystemMemory.targets b/pkg/test/packageSettings/System.Diagnostics.DiagnosticSource/workaroundMissingSystemMemory.targets deleted file mode 100644 index fdb725fd625f..000000000000 --- a/pkg/test/packageSettings/System.Diagnostics.DiagnosticSource/workaroundMissingSystemMemory.targets +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - diff --git a/pkg/test/packageSettings/System.IO.Ports/netcoreapp1.0/workaroundDowngrade.targets b/pkg/test/packageSettings/System.IO.Ports/netcoreapp1.0/workaroundDowngrade.targets deleted file mode 100644 index 2a4b06900c28..000000000000 --- a/pkg/test/packageSettings/System.IO.Ports/netcoreapp1.0/workaroundDowngrade.targets +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/pkg/test/packageSettings/System.IO.Ports/workaroundDowngrade.targets b/pkg/test/packageSettings/System.IO.Ports/workaroundDowngrade.targets new file mode 100644 index 000000000000..37e8334cafc9 --- /dev/null +++ b/pkg/test/packageSettings/System.IO.Ports/workaroundDowngrade.targets @@ -0,0 +1,6 @@ + + + + + + diff --git a/pkg/test/packageTest.targets b/pkg/test/packageTest.targets index d0f78b37cc08..f3e2d7efa671 100644 --- a/pkg/test/packageTest.targets +++ b/pkg/test/packageTest.targets @@ -8,14 +8,13 @@ https://api.nuget.org/v3/index.json; https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json; - https://dotnet.myget.org/F/roslyn-tools/api/v3/index.json; $(LocalPackagesPath) - + diff --git a/pkg/test/testPackages.proj b/pkg/test/testPackages.proj index 466c9005e835..da1e0ecd6a56 100644 --- a/pkg/test/testPackages.proj +++ b/pkg/test/testPackages.proj @@ -3,7 +3,7 @@ - + @@ -40,7 +40,7 @@ - + $(TestToolsDir)%(RecursiveDir) @@ -52,7 +52,7 @@ $(TestToolsDir)eng/ - + $(TestToolsDir)%(RecursiveDir) diff --git a/src/Common/src/CoreLib/Internal/IO/File.Unix.cs b/src/Common/src/CoreLib/Internal/IO/File.Unix.cs index 25d62003de8c..50fa0f0d0c4b 100644 --- a/src/Common/src/CoreLib/Internal/IO/File.Unix.cs +++ b/src/Common/src/CoreLib/Internal/IO/File.Unix.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Internal.IO { internal static partial class File diff --git a/src/Common/src/CoreLib/Internal/IO/File.Windows.cs b/src/Common/src/CoreLib/Internal/IO/File.Windows.cs index 28624bb95f32..0acae3b4577d 100644 --- a/src/Common/src/CoreLib/Internal/IO/File.Windows.cs +++ b/src/Common/src/CoreLib/Internal/IO/File.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.IO; diff --git a/src/Common/src/CoreLib/Internal/IO/File.cs b/src/Common/src/CoreLib/Internal/IO/File.cs index a8439895b1bd..a21f4954d4de 100644 --- a/src/Common/src/CoreLib/Internal/IO/File.cs +++ b/src/Common/src/CoreLib/Internal/IO/File.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Diagnostics; using System.Security; diff --git a/src/Common/src/CoreLib/Internal/Padding.cs b/src/Common/src/CoreLib/Internal/Padding.cs index 86050b7fb75c..14bf998babaa 100644 --- a/src/Common/src/CoreLib/Internal/Padding.cs +++ b/src/Common/src/CoreLib/Internal/Padding.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; namespace Internal diff --git a/src/Common/src/CoreLib/Internal/Resources/PRIExceptionInfo.cs b/src/Common/src/CoreLib/Internal/Resources/PRIExceptionInfo.cs index 1ae4674a9813..2b097a9d939d 100644 --- a/src/Common/src/CoreLib/Internal/Resources/PRIExceptionInfo.cs +++ b/src/Common/src/CoreLib/Internal/Resources/PRIExceptionInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace Internal.Resources { public class PRIExceptionInfo diff --git a/src/Common/src/CoreLib/Internal/Resources/WindowsRuntimeResourceManagerBase.cs b/src/Common/src/CoreLib/Internal/Resources/WindowsRuntimeResourceManagerBase.cs index 531b0fd4e602..173b2372c959 100644 --- a/src/Common/src/CoreLib/Internal/Resources/WindowsRuntimeResourceManagerBase.cs +++ b/src/Common/src/CoreLib/Internal/Resources/WindowsRuntimeResourceManagerBase.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Globalization; namespace Internal.Resources diff --git a/src/Common/src/CoreLib/Internal/Runtime/CompilerServices/Unsafe.cs b/src/Common/src/CoreLib/Internal/Runtime/CompilerServices/Unsafe.cs index 02092af2094d..4688933881af 100644 --- a/src/Common/src/CoreLib/Internal/Runtime/CompilerServices/Unsafe.cs +++ b/src/Common/src/CoreLib/Internal/Runtime/CompilerServices/Unsafe.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.CompilerServices; using System.Runtime.Versioning; diff --git a/src/Common/src/CoreLib/Internal/Threading/Tasks/AsyncCausalitySupport.cs b/src/Common/src/CoreLib/Internal/Threading/Tasks/AsyncCausalitySupport.cs index 54df96db664a..dcea41dbab22 100644 --- a/src/Common/src/CoreLib/Internal/Threading/Tasks/AsyncCausalitySupport.cs +++ b/src/Common/src/CoreLib/Internal/Threading/Tasks/AsyncCausalitySupport.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Threading.Tasks; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/Internal/Win32/RegistryKey.cs b/src/Common/src/CoreLib/Internal/Win32/RegistryKey.cs index 469d67866a17..912ddceef3e8 100644 --- a/src/Common/src/CoreLib/Internal/Win32/RegistryKey.cs +++ b/src/Common/src/CoreLib/Internal/Win32/RegistryKey.cs @@ -2,11 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; @@ -220,7 +220,8 @@ public unsafe string[] GetValueNames() return GetValue(name, null); } - public object? GetValue(string name, object? defaultValue) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + [return: NotNullIfNotNull("defaultValue")] + public object? GetValue(string name, object? defaultValue) { object? data = defaultValue; int type = 0; @@ -370,7 +371,7 @@ public unsafe string[] GetValueNames() // make sure the string is null terminated before processing the data if (blob.Length > 0 && blob[blob.Length - 1] != (char)0) { - Array.Resize(ref blob!, blob.Length + 1); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + Array.Resize(ref blob!, blob.Length + 1); // TODO-NULLABLE: Remove ! when nullable attributes are respected } string[] strings = Array.Empty(); @@ -415,13 +416,13 @@ public unsafe string[] GetValueNames() { if (strings.Length == stringsCount) { - Array.Resize(ref strings!, stringsCount > 0 ? stringsCount * 2 : 4); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + Array.Resize(ref strings!, stringsCount > 0 ? stringsCount * 2 : 4); // TODO-NULLABLE: Remove ! when nullable attributes are respected } - strings![stringsCount++] = toAdd; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + strings![stringsCount++] = toAdd; // TODO-NULLABLE: Remove ! when nullable attributes are respected } } - Array.Resize(ref strings!, stringsCount); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + Array.Resize(ref strings!, stringsCount); // TODO-NULLABLE: Remove ! when nullable attributes are respected data = strings; } break; diff --git a/src/Common/src/CoreLib/Interop/Unix/Interop.Errors.cs b/src/Common/src/CoreLib/Interop/Unix/Interop.Errors.cs index a4a7a4344aa3..2e597e7cae45 100644 --- a/src/Common/src/CoreLib/Interop/Unix/Interop.Errors.cs +++ b/src/Common/src/CoreLib/Interop/Unix/Interop.Errors.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; @@ -146,9 +145,7 @@ internal string GetErrorMessage() return Interop.Sys.StrError(RawErrno); } -#pragma warning disable CS8609 // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 public override string ToString() -#pragma warning restore CS8609 { return $"RawErrno: {RawErrno} Error: {Error} GetErrorMessage: {GetErrorMessage()}"; // No localization required; text is member names used for debugging purposes } diff --git a/src/Common/src/CoreLib/Interop/Unix/Interop.Libraries.cs b/src/Common/src/CoreLib/Interop/Unix/Interop.Libraries.cs index 6c620bf03107..02d009244509 100644 --- a/src/Common/src/CoreLib/Interop/Unix/Interop.Libraries.cs +++ b/src/Common/src/CoreLib/Interop/Unix/Interop.Libraries.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable internal static partial class Interop { internal static partial class Libraries diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs index c5ec71a73d2f..764bdaf85afe 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Globalization; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Casing.cs b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Casing.cs index 2878161c9910..503a864d693c 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Casing.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Casing.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; using System.Security; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Collation.cs b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Collation.cs index 9d21d23acb08..aea7615e4e71 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Collation.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Collation.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Globalization; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ICU.cs b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ICU.cs index f122d519ba0d..a16c813b2f5a 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ICU.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ICU.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Idna.cs b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Idna.cs index 9a0cd923be01..89b6c3cebec0 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Idna.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Idna.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Locale.cs b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Locale.cs index 40de0991821a..b563752bc00d 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Locale.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Locale.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs index 2cfc3746ba4b..d442da0ea137 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; using System.Text; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs index d5261ac6ca32..4a9933f9291f 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable internal static partial class Interop { internal static partial class Globalization diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs index 583599fb1390..6c6926824621 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; using System.Text; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Utils.cs b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Utils.cs index 058f07efe1ae..627ab56c9187 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Utils.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Utils.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Diagnostics; using System.Buffers; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Access.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Access.cs index 62b212b8074a..a723f572a5b0 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Access.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Access.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ChDir.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ChDir.cs index ebfa8738c98c..3c66995182ac 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ChDir.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ChDir.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Close.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Close.cs index 0c5ca55d8c06..8d192398a036 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Close.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Close.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FLock.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FLock.cs index b4b5902920cd..22934a3e77d5 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FLock.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FLock.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FSync.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FSync.cs index 5660aecce5ee..e3ab97093135 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FSync.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FSync.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FTruncate.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FTruncate.cs index 6d6b36811193..5dad650362d0 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FTruncate.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FTruncate.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetCpuUtilization.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetCpuUtilization.cs index 701c01cd9cf3..a630a3e82c34 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetCpuUtilization.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetCpuUtilization.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -14,9 +13,9 @@ internal unsafe partial class Sys [StructLayout(LayoutKind.Sequential)] internal struct ProcessCpuInformation { - ulong lastRecordedCurrentTime; - ulong lastRecordedKernelTime; - ulong lastRecordedUserTime; + internal ulong lastRecordedCurrentTime; + internal ulong lastRecordedKernelTime; + internal ulong lastRecordedUserTime; } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetCpuUtilization")] diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetCwd.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetCwd.cs index 2951d441d2d8..f6412992b130 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetCwd.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetCwd.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Buffers; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetEUid.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetEUid.cs index 98f5545f902a..8b525fa32729 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetEUid.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetEUid.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetHostName.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetHostName.cs index 34fa14f35256..f2555b0fc827 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetHostName.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetHostName.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetPid.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetPid.cs index 2656753655e9..02d259db7d18 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetPid.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetPid.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetPwUid.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetPwUid.cs index cbab70a97194..28b2309d03ec 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetPwUid.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetPwUid.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetRandomBytes.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetRandomBytes.cs index 7956567e8ba1..e911b13583d7 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetRandomBytes.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetRandomBytes.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetSystemTimeAsTicks.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetSystemTimeAsTicks.cs index 35e37834e10e..f02ecac13b91 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetSystemTimeAsTicks.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetSystemTimeAsTicks.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal static partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetTimestamp.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetTimestamp.cs index d1669b60951e..b57c0cd175f0 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetTimestamp.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetTimestamp.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal static partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetUnixName.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetUnixName.cs index 02e08fd447c1..fb925b9dca92 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetUnixName.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetUnixName.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetUnixRelease.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetUnixRelease.cs index 5885de678fe5..5e41ae98046e 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetUnixRelease.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetUnixRelease.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal static partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LSeek.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LSeek.cs index 3f93192422b1..7f8df7c6bf9f 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LSeek.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LSeek.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LockFileRegion.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LockFileRegion.cs index ecc95c4dc6a0..1deb9a431320 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LockFileRegion.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LockFileRegion.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.MksTemps.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.MksTemps.cs index e9624591b31b..14c2d989130a 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.MksTemps.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.MksTemps.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.MountPoints.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.MountPoints.cs index c2d1b7946672..a2fe2078b69b 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.MountPoints.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.MountPoints.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Collections.Generic; using System.Runtime.InteropServices; @@ -28,13 +27,13 @@ internal static string[] GetAllMountPoints() { if (count == found.Length) { - Array.Resize(ref found!, count * 2); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + Array.Resize(ref found!, count * 2); // TODO-NULLABLE: Remove ! when nullable attributes are respected } found[count++] = Marshal.PtrToStringAnsi((IntPtr)name)!; }); } - Array.Resize(ref found!, count); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + Array.Resize(ref found!, count); // TODO-NULLABLE: Remove ! when nullable attributes are respected return found; } } diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Open.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Open.cs index e151c4cf75fd..a9a994c78c01 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Open.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Open.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.OpenFlags.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.OpenFlags.cs index ce5f9ad70fae..f9e54c3cbcf9 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.OpenFlags.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.OpenFlags.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; internal static partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PathConf.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PathConf.cs index 27d5095a16b4..7213cb02640f 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PathConf.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PathConf.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Permissions.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Permissions.cs index 5cddd425bcfb..f1d13787d257 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Permissions.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Permissions.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; internal static partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PosixFAdvise.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PosixFAdvise.cs index 3035c5ecb420..ad8b73aed211 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PosixFAdvise.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PosixFAdvise.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Read.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Read.cs index e835b7ff6599..233feabdbb69 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Read.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Read.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadDir.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadDir.cs index a55ca83204ce..cacb3664db07 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadDir.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadDir.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadLink.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadLink.cs index f78fd1a80692..9a2d7d1e79d9 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadLink.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadLink.cs @@ -61,4 +61,4 @@ internal static partial class Sys } while (true); } } -} \ No newline at end of file +} diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Stat.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Stat.cs index ff4699c78288..d06fbda71852 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Stat.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Stat.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.SysConf.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.SysConf.cs index 1482b2861476..be0c0dee7bb6 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.SysConf.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.SysConf.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal static partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.SysLog.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.SysLog.cs index 85eef433837f..6b6a74b7436b 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.SysLog.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.SysLog.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal static partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Unlink.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Unlink.cs index bbeb8896e873..829210fa7e03 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Unlink.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Unlink.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Write.cs b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Write.cs index 761cd1635361..fb06d463beb7 100644 --- a/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Write.cs +++ b/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Write.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; diff --git a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.ActivityControl.cs b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.ActivityControl.cs index 34df748d39ab..27dce5853861 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.ActivityControl.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.ActivityControl.cs @@ -2,9 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Runtime.InteropServices; - internal partial class Interop { internal partial class Advapi32 diff --git a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EVENT_INFO_CLASS.cs b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EVENT_INFO_CLASS.cs index a122002e9abe..36abdb41905e 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EVENT_INFO_CLASS.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EVENT_INFO_CLASS.cs @@ -2,9 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Runtime.InteropServices; - internal partial class Interop { internal partial class Advapi32 diff --git a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventSetInformation.cs b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventSetInformation.cs index 381cb661c37e..90286b27be63 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventSetInformation.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventSetInformation.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventTraceGuidsEx.cs b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventTraceGuidsEx.cs index c5f6f3b18790..0e7c3cc64510 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventTraceGuidsEx.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventTraceGuidsEx.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventUnregister.cs b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventUnregister.cs index f387b3a9ab5c..3fb5a75b1ae6 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventUnregister.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventUnregister.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventWriteString.cs b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventWriteString.cs index a00a2f3a2c99..4ee30f62de6e 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventWriteString.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.EventWriteString.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.LookupAccountNameW.cs b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.LookupAccountNameW.cs index bef8afa434bb..2aa5851a4aa2 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.LookupAccountNameW.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.LookupAccountNameW.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegCloseKey.cs b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegCloseKey.cs index e27966978231..375376d52a01 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegCloseKey.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegCloseKey.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegDeleteKeyEx.cs b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegDeleteKeyEx.cs index 01c4cea4086a..c949cc15ff1f 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegDeleteKeyEx.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegDeleteKeyEx.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else diff --git a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegFlushKey.cs b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegFlushKey.cs index 3a867a2e31be..fa56f483990a 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegFlushKey.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegFlushKey.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else diff --git a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegistryConstants.cs b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegistryConstants.cs index b358f9fee081..bdb89702f8c3 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegistryConstants.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Advapi32/Interop.RegistryConstants.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable internal partial class Interop { internal partial class Advapi32 diff --git a/src/Common/src/CoreLib/Interop/Windows/BCrypt/Interop.BCryptGenRandom.GetRandomBytes.cs b/src/Common/src/CoreLib/Interop/Windows/BCrypt/Interop.BCryptGenRandom.GetRandomBytes.cs index 50bc5281586c..4d75163d4b41 100644 --- a/src/Common/src/CoreLib/Interop/Windows/BCrypt/Interop.BCryptGenRandom.GetRandomBytes.cs +++ b/src/Common/src/CoreLib/Interop/Windows/BCrypt/Interop.BCryptGenRandom.GetRandomBytes.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs b/src/Common/src/CoreLib/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs index d877dd255ce1..9d072a3b01e6 100644 --- a/src/Common/src/CoreLib/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs +++ b/src/Common/src/CoreLib/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/BCrypt/Interop.NTSTATUS.cs b/src/Common/src/CoreLib/Interop/Windows/BCrypt/Interop.NTSTATUS.cs index 74079f8f80ad..29aaa2904bff 100644 --- a/src/Common/src/CoreLib/Interop/Windows/BCrypt/Interop.NTSTATUS.cs +++ b/src/Common/src/CoreLib/Interop/Windows/BCrypt/Interop.NTSTATUS.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Crypt32/Interop.CryptProtectMemory.cs b/src/Common/src/CoreLib/Interop/Windows/Crypt32/Interop.CryptProtectMemory.cs index a60dc8eeecac..b10cb6a0410b 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Crypt32/Interop.CryptProtectMemory.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Crypt32/Interop.CryptProtectMemory.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; using System.Security; diff --git a/src/Common/src/CoreLib/Interop/Windows/Interop.BOOL.cs b/src/Common/src/CoreLib/Interop/Windows/Interop.BOOL.cs index 8a89556e59b0..9f4dab8935d2 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Interop.BOOL.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Interop.BOOL.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable internal partial class Interop { /// diff --git a/src/Common/src/CoreLib/Interop/Windows/Interop.BOOLEAN.cs b/src/Common/src/CoreLib/Interop/Windows/Interop.BOOLEAN.cs index 154ecbec7275..4874734534df 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Interop.BOOLEAN.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Interop.BOOLEAN.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable internal partial class Interop { /// diff --git a/src/Common/src/CoreLib/Interop/Windows/Interop.Errors.cs b/src/Common/src/CoreLib/Interop/Windows/Interop.Errors.cs index ea9ce0b8a35a..2e4683dfd70a 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Interop.Errors.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Interop.Errors.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable internal partial class Interop { // As defined in winerror.h and https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx diff --git a/src/Common/src/CoreLib/Interop/Windows/Interop.Libraries.cs b/src/Common/src/CoreLib/Interop/Windows/Interop.Libraries.cs index 80321fb07af8..8cbc8bfb266b 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Interop.Libraries.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Interop.Libraries.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable internal static partial class Interop { internal static partial class Libraries diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs index 3330d32f9a89..16365ee65119 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.IO; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CancelIoEx.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CancelIoEx.cs index 85809e1ed202..fc99e3052f6d 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CancelIoEx.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CancelIoEx.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Threading; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CloseHandle.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CloseHandle.cs index fd194166709f..ff41f939f1c6 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CloseHandle.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CloseHandle.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Constants.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Constants.cs index dc7dfef34e9e..b13cdfd03fed 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Constants.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Constants.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable internal static partial class Interop { internal static partial class Kernel32 diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CreateFile.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CreateFile.cs index 99ef2b28d792..de68a36cb997 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CreateFile.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CreateFile.cs @@ -2,10 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; -using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; @@ -35,9 +33,8 @@ internal static SafeFileHandle CreateFile( int dwFlagsAndAttributes, IntPtr hTemplateFile) { - string? lpFileNameWithPrefix = PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName); - Debug.Assert(lpFileNameWithPrefix != null, "null not expected when non-null passed"); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 - return CreateFilePrivate(lpFileNameWithPrefix, dwDesiredAccess, dwShareMode, ref securityAttrs, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); + lpFileName = PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName)!; // TODO-NULLABLE: Remove ! when nullable attributes are respected + return CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, ref securityAttrs, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); } } } diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CreateFile2.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CreateFile2.cs index fc9806132269..49e7485c00c8 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CreateFile2.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.CreateFile2.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; +using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; @@ -26,7 +26,7 @@ internal static SafeFileHandle CreateFile2( FileMode dwCreationDisposition, ref Kernel32.CREATEFILE2_EXTENDED_PARAMETERS pCreateExParams) { - lpFileName = PathInternal.EnsureExtendedPrefixOverMaxPath(lpFileName); + lpFileName = PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName)!; // TODO-NULLABLE: Remove ! when nullable attributes are respected return CreateFile2Private(lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, ref pCreateExParams); } } diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.EventWaitHandle.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.EventWaitHandle.cs index 8ff166c95845..dabe8c2dc2bd 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.EventWaitHandle.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.EventWaitHandle.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ExpandEnvironmentStrings.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ExpandEnvironmentStrings.cs index 67804d4a737b..ce3db6f2b458 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ExpandEnvironmentStrings.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ExpandEnvironmentStrings.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FILE_INFO_BY_HANDLE_CLASS.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FILE_INFO_BY_HANDLE_CLASS.cs index c619115fdd49..e31a453ba943 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FILE_INFO_BY_HANDLE_CLASS.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FILE_INFO_BY_HANDLE_CLASS.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/Interop/Windows/Kernel32/Interop.FILE_TIME.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FILE_TIME.cs similarity index 100% rename from src/Common/src/Interop/Windows/Kernel32/Interop.FILE_TIME.cs rename to src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FILE_TIME.cs diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FileAttributes.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FileAttributes.cs index 8103870deae8..725a25a7193a 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FileAttributes.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FileAttributes.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable internal partial class Interop { internal partial class Kernel32 diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FileTimeToSystemTime.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FileTimeToSystemTime.cs index f8c1be93f5b7..067ee715870c 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FileTimeToSystemTime.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FileTimeToSystemTime.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FileTypes.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FileTypes.cs index a4330f53389b..9d52f1f4f42d 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FileTypes.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FileTypes.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable internal partial class Interop { internal partial class Kernel32 diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FindClose.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FindClose.cs index de11958fe369..fcf9254acaae 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FindClose.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FindClose.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FindFirstFileEx.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FindFirstFileEx.cs index 80fb2e7189fc..52dcd54c9e05 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FindFirstFileEx.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FindFirstFileEx.cs @@ -21,11 +21,10 @@ internal partial class Kernel32 internal static SafeFindHandle FindFirstFile(string fileName, ref WIN32_FIND_DATA data) { - string? fileNameWithPrefix = PathInternal.EnsureExtendedPrefixIfNeeded(fileName); - Debug.Assert(fileNameWithPrefix != null, "null not expected when non-null passed"); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + fileName = PathInternal.EnsureExtendedPrefixIfNeeded(fileName)!; // TODO-NULLABLE: Remove ! when nullable attributes are respected // use FindExInfoBasic since we don't care about short name and it has better perf - return FindFirstFileExPrivate(fileNameWithPrefix, FINDEX_INFO_LEVELS.FindExInfoBasic, ref data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, 0); + return FindFirstFileExPrivate(fileName, FINDEX_INFO_LEVELS.FindExInfoBasic, ref data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, 0); } internal enum FINDEX_INFO_LEVELS : uint diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FlushFileBuffers.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FlushFileBuffers.cs index 5d0f0dcea7cc..e10a2279cff1 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FlushFileBuffers.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FlushFileBuffers.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FormatMessage.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FormatMessage.cs index bfa40819a1e0..09001e81e064 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FormatMessage.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FormatMessage.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FreeEnvironmentStrings.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FreeEnvironmentStrings.cs index 7c317e2665a9..c372a8553ecb 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FreeEnvironmentStrings.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FreeEnvironmentStrings.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FreeLibrary.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FreeLibrary.cs index b6b8ed670182..c70865350aeb 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FreeLibrary.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.FreeLibrary.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/Interop/Windows/Kernel32/Interop.GET_FILEEX_INFO_LEVELS.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GET_FILEEX_INFO_LEVELS.cs similarity index 100% rename from src/Common/src/Interop/Windows/Kernel32/Interop.GET_FILEEX_INFO_LEVELS.cs rename to src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GET_FILEEX_INFO_LEVELS.cs diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCPInfo.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCPInfo.cs index 98537ec330b8..8d523e41e9ac 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCPInfo.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCPInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentDirectory.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentDirectory.cs index 2f2eb48bbd5e..611cc70d289d 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentDirectory.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentDirectory.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentProcessId.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentProcessId.cs index b71fb4e6f22f..3a1a353d8620 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentProcessId.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentProcessId.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentProcess_IntPtr.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentProcess_IntPtr.cs index 7b9ea6661897..c99351950a83 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentProcess_IntPtr.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentProcess_IntPtr.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentThreadId.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentThreadId.cs index 0599f4c59023..d456db752257 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentThreadId.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetCurrentThreadId.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetEnvironmentStrings.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetEnvironmentStrings.cs index 9d25bed4800e..29a686026a27 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetEnvironmentStrings.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetEnvironmentStrings.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetEnvironmentVariable.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetEnvironmentVariable.cs index d591219b12ae..13adefc21634 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetEnvironmentVariable.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetEnvironmentVariable.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFileAttributesEx.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFileAttributesEx.cs index 624404952f77..e3f18fe6c087 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFileAttributesEx.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFileAttributesEx.cs @@ -21,77 +21,8 @@ internal partial class Kernel32 internal static bool GetFileAttributesEx(string name, GET_FILEEX_INFO_LEVELS fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation) { - string? nameWithExtendedPrefix = PathInternal.EnsureExtendedPrefixIfNeeded(name); - Debug.Assert(nameWithExtendedPrefix != null, "null not expected when non-null is passed"); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 - return GetFileAttributesExPrivate(nameWithExtendedPrefix, fileInfoLevel, ref lpFileInformation); - } - - internal enum GET_FILEEX_INFO_LEVELS : uint - { - GetFileExInfoStandard = 0x0u, - GetFileExMaxInfoLevel = 0x1u, - } - - internal struct WIN32_FILE_ATTRIBUTE_DATA - { - internal int dwFileAttributes; - internal uint ftCreationTimeLow; - internal uint ftCreationTimeHigh; - internal uint ftLastAccessTimeLow; - internal uint ftLastAccessTimeHigh; - internal uint ftLastWriteTimeLow; - internal uint ftLastWriteTimeHigh; - internal uint fileSizeHigh; - internal uint fileSizeLow; - - internal void PopulateFrom(ref WIN32_FIND_DATA findData) - { - // Copy the information to data - dwFileAttributes = (int)findData.dwFileAttributes; - ftCreationTimeLow = findData.ftCreationTime.dwLowDateTime; - ftCreationTimeHigh = findData.ftCreationTime.dwHighDateTime; - ftLastAccessTimeLow = findData.ftLastAccessTime.dwLowDateTime; - ftLastAccessTimeHigh = findData.ftLastAccessTime.dwHighDateTime; - ftLastWriteTimeLow = findData.ftLastWriteTime.dwLowDateTime; - ftLastWriteTimeHigh = findData.ftLastWriteTime.dwHighDateTime; - fileSizeHigh = findData.nFileSizeHigh; - fileSizeLow = findData.nFileSizeLow; - } - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - [BestFitMapping(false)] - internal unsafe struct WIN32_FIND_DATA - { - internal uint dwFileAttributes; - internal FILE_TIME ftCreationTime; - internal FILE_TIME ftLastAccessTime; - internal FILE_TIME ftLastWriteTime; - internal uint nFileSizeHigh; - internal uint nFileSizeLow; - internal uint dwReserved0; - internal uint dwReserved1; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] - internal string? cFileName; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] - internal string? cAlternateFileName; - } - - internal struct FILE_TIME - { - internal uint dwLowDateTime; - internal uint dwHighDateTime; - - internal FILE_TIME(long fileTime) - { - dwLowDateTime = (uint)fileTime; - dwHighDateTime = (uint)(fileTime >> 32); - } - - internal long ToTicks() - { - return ((long)dwHighDateTime << 32) + dwLowDateTime; - } + name = PathInternal.EnsureExtendedPrefixIfNeeded(name)!; // TODO-NULLABLE: Remove ! when nullable attributes are respected + return GetFileAttributesExPrivate(name, fileInfoLevel, ref lpFileInformation); } } } diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFileInformationByHandleEx.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFileInformationByHandleEx.cs index 78c9e7071fe0..1106cff1c58f 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFileInformationByHandleEx.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFileInformationByHandleEx.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs index 3f9e6271b5b5..faa57cc2f121 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs index 38b7cdd2e63f..197b0a9be523 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetLogicalDrives.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetLogicalDrives.cs index c69f7d30c204..657188f255e2 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetLogicalDrives.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetLogicalDrives.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs index dd497bf6d92c..81b4d096f564 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetProcessInformation.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetProcessInformation.cs index 76027483f23a..22e056937548 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetProcessInformation.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetProcessInformation.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetProcessTimes.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetProcessTimes.cs index 7b72ca773207..03c6c080c7d9 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetProcessTimes.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetProcessTimes.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetStdHandle.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetStdHandle.cs index ae54f641d60d..f2b54c9728a2 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetStdHandle.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetStdHandle.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemDirectoryW.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemDirectoryW.cs index a7cd273098c3..197f6f5eadcd 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemDirectoryW.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemDirectoryW.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal static partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemInfo.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemInfo.cs index 56210558d2d1..cbf07eae7ffa 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemInfo.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTime.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTime.cs index b51cfa396e1a..710db5e4b99f 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTime.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTime.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTimeAsFileTime.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTimeAsFileTime.cs index 70363ce6961f..e2dcd906c2ad 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTimeAsFileTime.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTimeAsFileTime.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTimePreciseAsFileTime.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTimePreciseAsFileTime.cs index 8c86d952870b..e3262799d132 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTimePreciseAsFileTime.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTimePreciseAsFileTime.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTimes.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTimes.cs index 12d5a4aa57d4..d9e858062c7d 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTimes.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetSystemTimes.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs index 0afc4481be75..97e1d82847a6 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetTempPathW.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetTempPathW.cs index 68ff9aca40f8..7f7bb775c85a 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetTempPathW.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetTempPathW.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetVersionExW.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetVersionExW.cs index ab79ed2ea4f7..13a997a34400 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetVersionExW.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetVersionExW.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GlobalMemoryStatusEx.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GlobalMemoryStatusEx.cs index 99dde8581597..6a87ec370b24 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GlobalMemoryStatusEx.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GlobalMemoryStatusEx.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Globalization.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Globalization.cs index 1312454eabbd..49d8033e542a 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Globalization.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Globalization.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; @@ -102,8 +101,8 @@ internal static extern unsafe bool IsNLSDefinedString( int cchStr); #if !ENABLE_WINRT - [DllImport("Kernel32.dll", CharSet = CharSet.Auto)] - internal static extern bool GetUserPreferredUILanguages(uint dwFlags, out uint pulNumLanguages, char[]? pwszLanguagesBuffer, ref uint pcchLanguagesBuffer); + [DllImport("kernel32.dll", CharSet = CharSet.Auto)] + internal static extern Interop.BOOL GetUserPreferredUILanguages(uint dwFlags, uint* pulNumLanguages, char* pwszLanguagesBuffer, uint* pcchLanguagesBuffer); #endif //!ENABLE_WINRT [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.HandleTypes.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.HandleTypes.cs index 51f7c92f024f..c2096aa62b75 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.HandleTypes.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.HandleTypes.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable internal partial class Interop { internal partial class Kernel32 diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.IsWow64Process_IntPtr.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.IsWow64Process_IntPtr.cs index 5d064780bfec..7953da68daa5 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.IsWow64Process_IntPtr.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.IsWow64Process_IntPtr.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.LoadLibraryEx.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.LoadLibraryEx.cs index c3c6fcc118d1..4eef5852fe7e 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.LoadLibraryEx.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.LoadLibraryEx.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.LocalAlloc.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.LocalAlloc.cs index 55f76b4403c5..9c74adbe01a5 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.LocalAlloc.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.LocalAlloc.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.LockFile.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.LockFile.cs index 7d0a55ce644f..a21d00f4f665 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.LockFile.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.LockFile.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.IO; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MAX_PATH.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MAX_PATH.cs index 0a05230f1328..f7fa32669bad 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MAX_PATH.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MAX_PATH.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable internal partial class Interop { internal partial class Kernel32 diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MEMORYSTATUSEX.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MEMORYSTATUSEX.cs index 8ddac8e64f48..45f57aa4d83b 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MEMORYSTATUSEX.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MEMORYSTATUSEX.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MEMORY_BASIC_INFORMATION.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MEMORY_BASIC_INFORMATION.cs index a14157fecc10..0744d53f66c5 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MEMORY_BASIC_INFORMATION.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MEMORY_BASIC_INFORMATION.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MUI.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MUI.cs index 024dd1fba49c..509d9a241107 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MUI.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MUI.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MultiByteToWideChar.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MultiByteToWideChar.cs index edabe9f9f6b9..158e4db3fd30 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MultiByteToWideChar.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.MultiByteToWideChar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Mutex.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Mutex.cs index ed25668a0001..46ddd12f9b43 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Mutex.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Mutex.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.OSVERSIONINFOEX.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.OSVERSIONINFOEX.cs index 19c32e07c183..1bfe00c57446 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.OSVERSIONINFOEX.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.OSVERSIONINFOEX.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.OutputDebugString.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.OutputDebugString.cs index bc7c1c83be5a..8da50ff8ab3a 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.OutputDebugString.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.OutputDebugString.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.QueryPerformanceCounter.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.QueryPerformanceCounter.cs index e0959f73daea..ddc9797e5f2a 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.QueryPerformanceCounter.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.QueryPerformanceCounter.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.QueryPerformanceFrequency.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.QueryPerformanceFrequency.cs index 71fd3db6cb70..72a48ba208be 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.QueryPerformanceFrequency.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.QueryPerformanceFrequency.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.QueryUnbiasedInterruptTime.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.QueryUnbiasedInterruptTime.cs index bdd77c180fb1..87ca7fd1d497 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.QueryUnbiasedInterruptTime.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.QueryUnbiasedInterruptTime.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_IntPtr.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_IntPtr.cs index 67e317adf060..076f7f136fde 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_IntPtr.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_IntPtr.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_NativeOverlapped.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_NativeOverlapped.cs index 0687830057c1..3ae65a88069e 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_NativeOverlapped.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_NativeOverlapped.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ResolveLocaleName.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ResolveLocaleName.cs index 1a0e61317ceb..2d6b6c3c729e 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ResolveLocaleName.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.ResolveLocaleName.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SECURITY_ATTRIBUTES.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SECURITY_ATTRIBUTES.cs index 16e9fec77394..8d31f8622ff4 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SECURITY_ATTRIBUTES.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SECURITY_ATTRIBUTES.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SYSTEM_INFO.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SYSTEM_INFO.cs index ab793a390b55..16e5bfd8da0c 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SYSTEM_INFO.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SYSTEM_INFO.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SecurityOptions.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SecurityOptions.cs index 4e94e3e5a856..4a4402484f2b 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SecurityOptions.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SecurityOptions.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable internal partial class Interop { internal partial class Kernel32 diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Semaphore.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Semaphore.cs index f453a255bdbf..cc2735945249 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Semaphore.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Semaphore.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetCurrentDirectory.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetCurrentDirectory.cs index 5cf23a8d471e..b30e5d765643 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetCurrentDirectory.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetCurrentDirectory.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetEndOfFile.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetEndOfFile.cs index 2233e1f83815..e5d60041a8ed 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetEndOfFile.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetEndOfFile.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetEnvironmentVariable.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetEnvironmentVariable.cs index 6a0fc1d4d96a..b94ec2111f5c 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetEnvironmentVariable.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetEnvironmentVariable.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetFilePointerEx.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetFilePointerEx.cs index dbedf85cbead..c0e5247a5233 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetFilePointerEx.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetFilePointerEx.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetThreadErrorMode.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetThreadErrorMode.cs index b5bd94508608..123eb75d7bee 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetThreadErrorMode.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SetThreadErrorMode.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SystemTimeToFileTime.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SystemTimeToFileTime.cs index cf81e3d29524..43db7b47164d 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SystemTimeToFileTime.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.SystemTimeToFileTime.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.TimeZone.Registry.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.TimeZone.Registry.cs index 30299ae709dd..062d1caebacc 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.TimeZone.Registry.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.TimeZone.Registry.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.TimeZone.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.TimeZone.cs index dc89af488a8c..68d4583b54a2 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.TimeZone.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.TimeZone.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.TzSpecificLocalTimeToSystemTime.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.TzSpecificLocalTimeToSystemTime.cs index e832e9341e6e..2cca7faed732 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.TzSpecificLocalTimeToSystemTime.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.TzSpecificLocalTimeToSystemTime.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VerSetConditionMask.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VerSetConditionMask.cs index 931faf5705da..385e48a43907 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VerSetConditionMask.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VerSetConditionMask.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VerifyVersionExW.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VerifyVersionExW.cs index 90f5bdbe103f..5c2471cf4952 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VerifyVersionExW.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VerifyVersionExW.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VirtualAlloc.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VirtualAlloc.cs index 944fb4e5eb62..a97dc1aec7bb 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VirtualAlloc.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VirtualAlloc.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VirtualFree.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VirtualFree.cs index 2b940a4210cf..574cd93a0a8f 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VirtualFree.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VirtualFree.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VirtualQuery.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VirtualQuery.cs index c7c02d687551..faab1cc81a61 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VirtualQuery.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.VirtualQuery.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/Interop/Windows/Kernel32/Interop.WIN32_FILE_ATTRIBUTE_DATA.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WIN32_FILE_ATTRIBUTE_DATA.cs similarity index 100% rename from src/Common/src/Interop/Windows/Kernel32/Interop.WIN32_FILE_ATTRIBUTE_DATA.cs rename to src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WIN32_FILE_ATTRIBUTE_DATA.cs diff --git a/src/Common/src/Interop/Windows/Kernel32/Interop.WIN32_FIND_DATA.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WIN32_FIND_DATA.cs similarity index 100% rename from src/Common/src/Interop/Windows/Kernel32/Interop.WIN32_FIND_DATA.cs rename to src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WIN32_FIND_DATA.cs diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WideCharToMultiByte.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WideCharToMultiByte.cs index 6e523e5b7b44..a06c9153f470 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WideCharToMultiByte.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WideCharToMultiByte.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs index 46948096ed72..69651ca1cab3 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_NativeOverlapped.cs b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_NativeOverlapped.cs index 6816d59028ef..dc1e97555b89 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_NativeOverlapped.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_NativeOverlapped.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Normaliz/Interop.Idna.cs b/src/Common/src/CoreLib/Interop/Windows/Normaliz/Interop.Idna.cs index 61b107bd5afc..f49ce8dd6170 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Normaliz/Interop.Idna.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Normaliz/Interop.Idna.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Normaliz/Interop.Normalization.cs b/src/Common/src/CoreLib/Interop/Windows/Normaliz/Interop.Normalization.cs index d7f639b9653a..84664d51cb08 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Normaliz/Interop.Normalization.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Normaliz/Interop.Normalization.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/NtDll/Interop.NtQuerySystemInformation.cs b/src/Common/src/CoreLib/Interop/Windows/NtDll/Interop.NtQuerySystemInformation.cs index 1115926bba43..16f05e338cd9 100644 --- a/src/Common/src/CoreLib/Interop/Windows/NtDll/Interop.NtQuerySystemInformation.cs +++ b/src/Common/src/CoreLib/Interop/Windows/NtDll/Interop.NtQuerySystemInformation.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Ole32/Interop.CoCreateGuid.cs b/src/Common/src/CoreLib/Interop/Windows/Ole32/Interop.CoCreateGuid.cs index db5c04aeff03..57accbe7c008 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Ole32/Interop.CoCreateGuid.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Ole32/Interop.CoCreateGuid.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/Ole32/Interop.CoTaskMemAlloc.cs b/src/Common/src/CoreLib/Interop/Windows/Ole32/Interop.CoTaskMemAlloc.cs index 335531d77a54..9119ee774e5f 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Ole32/Interop.CoTaskMemAlloc.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Ole32/Interop.CoTaskMemAlloc.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysAllocStringByteLen.cs b/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysAllocStringByteLen.cs index 6cec249eba59..846283a67420 100644 --- a/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysAllocStringByteLen.cs +++ b/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysAllocStringByteLen.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs b/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs index 67bd4f0bc05a..4980844deaac 100644 --- a/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs +++ b/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; using System.Security; diff --git a/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysFreeString.cs b/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysFreeString.cs index 8e1c9d8f2e4c..8673cc672411 100644 --- a/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysFreeString.cs +++ b/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysFreeString.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysStringLen.cs b/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysStringLen.cs index 7bd214ac6733..cf65d6b086cf 100644 --- a/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysStringLen.cs +++ b/src/Common/src/CoreLib/Interop/Windows/OleAut32/Interop.SysStringLen.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; using System.Security; diff --git a/src/Common/src/CoreLib/Interop/Windows/Secur32/Interop.GetUserNameExW.cs b/src/Common/src/CoreLib/Interop/Windows/Secur32/Interop.GetUserNameExW.cs index e91506bf4e43..cf0dd5f698fb 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Secur32/Interop.GetUserNameExW.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Secur32/Interop.GetUserNameExW.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/Common/src/CoreLib/Interop/Windows/Shell32/Interop.SHGetKnownFolderPath.cs b/src/Common/src/CoreLib/Interop/Windows/Shell32/Interop.SHGetKnownFolderPath.cs index c6bc10a95f81..1090805c0e04 100644 --- a/src/Common/src/CoreLib/Interop/Windows/Shell32/Interop.SHGetKnownFolderPath.cs +++ b/src/Common/src/CoreLib/Interop/Windows/Shell32/Interop.SHGetKnownFolderPath.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Interop/Windows/User32/Interop.Constants.cs b/src/Common/src/CoreLib/Interop/Windows/User32/Interop.Constants.cs index 2cc835fad951..f1f09740e90f 100644 --- a/src/Common/src/CoreLib/Interop/Windows/User32/Interop.Constants.cs +++ b/src/Common/src/CoreLib/Interop/Windows/User32/Interop.Constants.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable internal partial class Interop { internal partial class User32 diff --git a/src/Common/src/CoreLib/Interop/Windows/User32/Interop.LoadString.cs b/src/Common/src/CoreLib/Interop/Windows/User32/Interop.LoadString.cs index d7239a3c4ac0..078ebd481dd6 100644 --- a/src/Common/src/CoreLib/Interop/Windows/User32/Interop.LoadString.cs +++ b/src/Common/src/CoreLib/Interop/Windows/User32/Interop.LoadString.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; diff --git a/src/Common/src/CoreLib/Interop/Windows/User32/Interop.SendMessageTimeout.cs b/src/Common/src/CoreLib/Interop/Windows/User32/Interop.SendMessageTimeout.cs index 2c1bcc6c3222..c8a97e6b9dbf 100644 --- a/src/Common/src/CoreLib/Interop/Windows/User32/Interop.SendMessageTimeout.cs +++ b/src/Common/src/CoreLib/Interop/Windows/User32/Interop.SendMessageTimeout.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/CriticalHandleMinusOneIsInvalid.cs b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/CriticalHandleMinusOneIsInvalid.cs index 8576dacc3d0c..a76c51d96660 100644 --- a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/CriticalHandleMinusOneIsInvalid.cs +++ b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/CriticalHandleMinusOneIsInvalid.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/CriticalHandleZeroOrMinusOneIsInvalid.cs b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/CriticalHandleZeroOrMinusOneIsInvalid.cs index 2b61f6248ac0..28d021948962 100644 --- a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/CriticalHandleZeroOrMinusOneIsInvalid.cs +++ b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/CriticalHandleZeroOrMinusOneIsInvalid.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs index ec99cbf17eb3..602537a30561 100644 --- a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs +++ b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Diagnostics; using System.IO; diff --git a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs index db8482ed712c..a53046cc182a 100644 --- a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs +++ b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Security; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeFindHandle.Windows.cs b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeFindHandle.Windows.cs index 192f523ff162..4ba05409fd92 100644 --- a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeFindHandle.Windows.cs +++ b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeFindHandle.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Security; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeHandleMinusOneIsInvalid.cs b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeHandleMinusOneIsInvalid.cs index b146b5a68713..5415f2c35d31 100644 --- a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeHandleMinusOneIsInvalid.cs +++ b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeHandleMinusOneIsInvalid.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs index 9a58aa29fed2..8d0220bf905e 100644 --- a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs +++ b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs index dea7978ee8ec..3be2e354abf3 100644 --- a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs +++ b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace Microsoft.Win32.SafeHandles { sealed internal class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid diff --git a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs index 011aaeae662f..249f5e9f7c24 100644 --- a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs +++ b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs index c3a7fcad885d..37e350031b83 100644 --- a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs +++ b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System; diff --git a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs index e87fedd724a0..66f17f0af709 100644 --- a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs +++ b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace Microsoft.Win32.SafeHandles { public sealed partial class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid diff --git a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs index f2e81eacd8c5..edb0cdfcafe7 100644 --- a/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs +++ b/src/Common/src/CoreLib/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; namespace Microsoft.Win32.SafeHandles diff --git a/src/Common/src/CoreLib/System.Private.CoreLib.Shared.projitems b/src/Common/src/CoreLib/System.Private.CoreLib.Shared.projitems index e51a210baea6..0b8bddea5f52 100644 --- a/src/Common/src/CoreLib/System.Private.CoreLib.Shared.projitems +++ b/src/Common/src/CoreLib/System.Private.CoreLib.Shared.projitems @@ -7,6 +7,9 @@ + + enable + false false @@ -195,6 +198,7 @@ + @@ -528,6 +532,7 @@ + @@ -672,6 +677,7 @@ + @@ -699,6 +705,7 @@ + @@ -854,6 +861,7 @@ + @@ -1016,11 +1024,13 @@ + + @@ -1032,7 +1042,7 @@ - + @@ -1070,6 +1080,8 @@ + + @@ -1080,6 +1092,7 @@ + @@ -1100,6 +1113,7 @@ + @@ -1211,7 +1225,7 @@ - + @@ -1241,6 +1255,7 @@ + @@ -1265,6 +1280,7 @@ + diff --git a/src/Common/src/CoreLib/System/AccessViolationException.cs b/src/Common/src/CoreLib/System/AccessViolationException.cs index 357930898ca7..11590028d5a8 100644 --- a/src/Common/src/CoreLib/System/AccessViolationException.cs +++ b/src/Common/src/CoreLib/System/AccessViolationException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System; using System.Runtime.Serialization; diff --git a/src/Common/src/CoreLib/System/Action.cs b/src/Common/src/CoreLib/System/Action.cs index 4c840379c843..54ca7aaf5323 100644 --- a/src/Common/src/CoreLib/System/Action.cs +++ b/src/Common/src/CoreLib/System/Action.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { public delegate void Action(); diff --git a/src/Common/src/CoreLib/System/Activator.RuntimeType.cs b/src/Common/src/CoreLib/System/Activator.RuntimeType.cs index 224abdbcd451..bd7670f9e312 100644 --- a/src/Common/src/CoreLib/System/Activator.RuntimeType.cs +++ b/src/Common/src/CoreLib/System/Activator.RuntimeType.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Reflection; using System.Globalization; +using System.Runtime.Loader; using System.Runtime.Remoting; using System.Threading; @@ -111,14 +111,9 @@ public static partial class Activator } else { - RuntimeAssembly? assemblyFromResolveEvent; - AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(assemblyString, out assemblyFromResolveEvent); - if (assemblyFromResolveEvent != null) - { - // Assembly was resolved via AssemblyResolve event - assembly = assemblyFromResolveEvent; - } - else if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime) + AssemblyName assemblyName = new AssemblyName(assemblyString); + + if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime) { // WinRT type - we have to use Type.GetType type = Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, ignoreCase); @@ -127,7 +122,7 @@ public static partial class Activator { // Classic managed type assembly = RuntimeAssembly.InternalLoadAssemblyName( - assemblyName, ref stackMark); + assemblyName, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext); } } diff --git a/src/Common/src/CoreLib/System/Activator.cs b/src/Common/src/CoreLib/System/Activator.cs index b4e5ddfeea24..8d6610f6a94f 100644 --- a/src/Common/src/CoreLib/System/Activator.cs +++ b/src/Common/src/CoreLib/System/Activator.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Globalization; using System.Reflection; diff --git a/src/Common/src/CoreLib/System/AggregateException.cs b/src/Common/src/CoreLib/System/AggregateException.cs index d0043cfc908a..08cda7c38834 100644 --- a/src/Common/src/CoreLib/System/AggregateException.cs +++ b/src/Common/src/CoreLib/System/AggregateException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Collections.Generic; using System.Collections.ObjectModel; diff --git a/src/Common/src/CoreLib/System/AppContext.cs b/src/Common/src/CoreLib/System/AppContext.cs index fcda485fa149..7f81a4346753 100644 --- a/src/Common/src/CoreLib/System/AppContext.cs +++ b/src/Common/src/CoreLib/System/AppContext.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections.Generic; using System.Reflection; using System.Runtime.ExceptionServices; @@ -127,7 +126,7 @@ public static void SetSwitch(string switchName, bool isEnabled) Interlocked.CompareExchange(ref s_switches, new Dictionary(), null); } - lock (s_switches!) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + lock (s_switches!) // TODO-NULLABLE: Remove ! when compiler specially-recognizes CompareExchange for nullability { s_switches[switchName] = isEnabled; } diff --git a/src/Common/src/CoreLib/System/AppDomain.Unix.cs b/src/Common/src/CoreLib/System/AppDomain.Unix.cs new file mode 100644 index 000000000000..3c1ef889f97b --- /dev/null +++ b/src/Common/src/CoreLib/System/AppDomain.Unix.cs @@ -0,0 +1,26 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System +{ + public sealed partial class AppDomain + { + public TimeSpan MonitoringTotalProcessorTime + { + get + { + Interop.Sys.ProcessCpuInformation cpuInfo = default; + Interop.Sys.GetCpuUtilization(ref cpuInfo); + + ulong userTime100Nanoseconds = cpuInfo.lastRecordedUserTime / 100; // nanoseconds to 100-nanoseconds + if (userTime100Nanoseconds > long.MaxValue) + { + userTime100Nanoseconds = long.MaxValue; + } + + return new TimeSpan((long)userTime100Nanoseconds); + } + } + } +} diff --git a/src/Common/src/CoreLib/System/AppDomain.Windows.cs b/src/Common/src/CoreLib/System/AppDomain.Windows.cs new file mode 100644 index 000000000000..07633273e243 --- /dev/null +++ b/src/Common/src/CoreLib/System/AppDomain.Windows.cs @@ -0,0 +1,14 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System +{ + public sealed partial class AppDomain + { + public TimeSpan MonitoringTotalProcessorTime => + Interop.Kernel32.GetProcessTimes(Interop.Kernel32.GetCurrentProcess(), out _, out _, out _, out long userTime100Nanoseconds) ? + new TimeSpan(userTime100Nanoseconds) : + TimeSpan.Zero; + } +} diff --git a/src/Common/src/CoreLib/System/AppDomain.cs b/src/Common/src/CoreLib/System/AppDomain.cs index b1a20551b5e9..2d8cd9c57680 100644 --- a/src/Common/src/CoreLib/System/AppDomain.cs +++ b/src/Common/src/CoreLib/System/AppDomain.cs @@ -4,7 +4,6 @@ #pragma warning disable CS0067 // events are declared but not used -#nullable enable using System.Diagnostics; using System.IO; using System.Reflection; @@ -185,26 +184,28 @@ public static void Unload(AppDomain domain) public static bool MonitoringIsEnabled { - get { return false; } + get { return true; } set { if (!value) { throw new ArgumentException(SR.Arg_MustBeTrue); } - throw new PlatformNotSupportedException(SR.PlatformNotSupported_AppDomain_ResMon); } } - public long MonitoringSurvivedMemorySize { get { throw CreateResMonNotAvailException(); } } + public long MonitoringSurvivedMemorySize => MonitoringSurvivedProcessMemorySize; - public static long MonitoringSurvivedProcessMemorySize { get { throw CreateResMonNotAvailException(); } } - - public long MonitoringTotalAllocatedMemorySize { get { throw CreateResMonNotAvailException(); } } - - public TimeSpan MonitoringTotalProcessorTime { get { throw CreateResMonNotAvailException(); } } + public static long MonitoringSurvivedProcessMemorySize + { + get + { + GCMemoryInfo mi = GC.GetGCMemoryInfo(); + return mi.HeapSizeBytes - mi.FragmentedBytes; + } + } - private static Exception CreateResMonNotAvailException() => new InvalidOperationException(SR.PlatformNotSupported_AppDomain_ResMon); + public long MonitoringTotalAllocatedMemorySize => GC.GetTotalAllocatedBytes(precise: false); [ObsoleteAttribute("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread. https://go.microsoft.com/fwlink/?linkid=14202", false)] public static int GetCurrentThreadId() => Environment.CurrentManagedThreadId; @@ -389,7 +390,7 @@ public void SetThreadPrincipal(IPrincipal principal) return oh?.Unwrap(); } - public IPrincipal? GetThreadPrincipal() + internal IPrincipal? GetThreadPrincipal() { IPrincipal? principal = _defaultPrincipal; if (principal == null) @@ -399,8 +400,8 @@ public void SetThreadPrincipal(IPrincipal principal) case PrincipalPolicy.UnauthenticatedPrincipal: if (s_getUnauthenticatedPrincipal == null) { - Type type = Type.GetType("System.Security.Principal.GenericPrincipal, System.Security.Claims", throwOnError: true); - MethodInfo mi = type.GetMethod("GetDefaultInstance", BindingFlags.NonPublic | BindingFlags.Static); + Type type = Type.GetType("System.Security.Principal.GenericPrincipal, System.Security.Claims", throwOnError: true)!; + MethodInfo? mi = type.GetMethod("GetDefaultInstance", BindingFlags.NonPublic | BindingFlags.Static); Debug.Assert(mi != null); // Don't throw PNSE if null like for WindowsPrincipal as UnauthenticatedPrincipal should // be available on all platforms. @@ -408,14 +409,14 @@ public void SetThreadPrincipal(IPrincipal principal) (Func)mi.CreateDelegate(typeof(Func))); } - principal = s_getUnauthenticatedPrincipal!(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + principal = s_getUnauthenticatedPrincipal!(); // TODO-NULLABLE: Remove ! when nullable attributes are respected break; case PrincipalPolicy.WindowsPrincipal: if (s_getWindowsPrincipal == null) { - Type type = Type.GetType("System.Security.Principal.WindowsPrincipal, System.Security.Principal.Windows", throwOnError: true); - MethodInfo mi = type.GetMethod("GetDefaultInstance", BindingFlags.NonPublic | BindingFlags.Static); + Type type = Type.GetType("System.Security.Principal.WindowsPrincipal, System.Security.Principal.Windows", throwOnError: true)!; + MethodInfo? mi = type.GetMethod("GetDefaultInstance", BindingFlags.NonPublic | BindingFlags.Static); if (mi == null) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Principal); @@ -424,7 +425,7 @@ public void SetThreadPrincipal(IPrincipal principal) (Func)mi.CreateDelegate(typeof(Func))); } - principal = s_getWindowsPrincipal!(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + principal = s_getWindowsPrincipal!(); // TODO-NULLABLE: Remove ! when nullable attributes are respected break; } } diff --git a/src/Common/src/CoreLib/System/AppDomainSetup.cs b/src/Common/src/CoreLib/System/AppDomainSetup.cs index e8d0b9fff4f3..4537dcdf94e5 100644 --- a/src/Common/src/CoreLib/System/AppDomainSetup.cs +++ b/src/Common/src/CoreLib/System/AppDomainSetup.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { #if PROJECTN diff --git a/src/Common/src/CoreLib/System/ApplicationException.cs b/src/Common/src/CoreLib/System/ApplicationException.cs index 5042b112cdbd..875b54a2a6a2 100644 --- a/src/Common/src/CoreLib/System/ApplicationException.cs +++ b/src/Common/src/CoreLib/System/ApplicationException.cs @@ -12,7 +12,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/ArgumentException.cs b/src/Common/src/CoreLib/System/ArgumentException.cs index be7ffbe7fa70..6e38c7b3f2d1 100644 --- a/src/Common/src/CoreLib/System/ArgumentException.cs +++ b/src/Common/src/CoreLib/System/ArgumentException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System.Globalization; using System.Runtime.Serialization; diff --git a/src/Common/src/CoreLib/System/ArgumentNullException.cs b/src/Common/src/CoreLib/System/ArgumentNullException.cs index 206c1a055bed..bf0d205fe701 100644 --- a/src/Common/src/CoreLib/System/ArgumentNullException.cs +++ b/src/Common/src/CoreLib/System/ArgumentNullException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/ArgumentOutOfRangeException.cs b/src/Common/src/CoreLib/System/ArgumentOutOfRangeException.cs index 7ca9085c6335..8c47541b10d4 100644 --- a/src/Common/src/CoreLib/System/ArgumentOutOfRangeException.cs +++ b/src/Common/src/CoreLib/System/ArgumentOutOfRangeException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System.Globalization; using System.Runtime.Serialization; diff --git a/src/Common/src/CoreLib/System/ArithmeticException.cs b/src/Common/src/CoreLib/System/ArithmeticException.cs index 5521c39a2f5a..a5028dbd79b2 100644 --- a/src/Common/src/CoreLib/System/ArithmeticException.cs +++ b/src/Common/src/CoreLib/System/ArithmeticException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/Array.Enumerators.cs b/src/Common/src/CoreLib/System/Array.Enumerators.cs index 4547af13dda5..dd46dc82d8d8 100644 --- a/src/Common/src/CoreLib/System/Array.Enumerators.cs +++ b/src/Common/src/CoreLib/System/Array.Enumerators.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/Common/src/CoreLib/System/Array.cs b/src/Common/src/CoreLib/System/Array.cs index 058f1ca8e214..11479d88e28d 100644 --- a/src/Common/src/CoreLib/System/Array.cs +++ b/src/Common/src/CoreLib/System/Array.cs @@ -6,10 +6,11 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; -#nullable enable namespace System { [Serializable] @@ -36,10 +37,10 @@ public static ReadOnlyCollection AsReadOnly(T[] array) } // T[] implements IList. - return new ReadOnlyCollection(array); + return new ReadOnlyCollection(array!); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } - public static void Resize(ref T[]? array, int newSize) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + public static void Resize([NotNull] ref T[]? array, int newSize) { if (newSize < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.newSize, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); @@ -65,7 +66,7 @@ public static Array CreateInstance(Type elementType, params long[] lengths) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); } - if (lengths!.Length == 0) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (lengths!.Length == 0) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank); int[] intLengths = new int[lengths.Length]; @@ -149,7 +150,7 @@ public static void Copy(Array sourceArray, long sourceIndex, Array destinationAr { if (indices == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); - if (Rank != indices!.Length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (Rank != indices!.Length) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); int[] intIndices = new int[indices.Length]; @@ -189,7 +190,7 @@ public void SetValue(object? value, long index1, long index2) this.SetValue(value, iindex1, iindex2); } - public void SetValue(object value, long index1, long index2, long index3) + public void SetValue(object? value, long index1, long index2, long index3) { int iindex1 = (int)index1; int iindex2 = (int)index2; @@ -209,7 +210,7 @@ public void SetValue(object? value, params long[] indices) { if (indices == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); - if (Rank != indices!.Length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (Rank != indices!.Length) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); int[] intIndices = new int[indices.Length]; @@ -324,7 +325,7 @@ int IStructuralComparable.CompareTo(object? other, IComparer comparer) int i = 0; int c = 0; - while (i < o!.Length && c == 0) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + while (i < o!.Length && c == 0) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { object? left = GetValue(i); object? right = o.GetValue(i); @@ -383,7 +384,7 @@ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) for (int i = (this.Length >= 8 ? this.Length - 8 : 0); i < this.Length; i++) { - ret = CombineHashCodes(ret, comparer!.GetHashCode(GetValue(i))); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + ret = CombineHashCodes(ret, comparer!.GetHashCode(GetValue(i)!)); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } return ret; @@ -406,7 +407,7 @@ public static int BinarySearch(Array array, object? value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - return BinarySearch(array!, array!.GetLowerBound(0), array.Length, value, null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return BinarySearch(array!, array!.GetLowerBound(0), array.Length, value, null); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } // Searches a section of an array for a given element using a binary search @@ -445,7 +446,7 @@ public static int BinarySearch(Array array, object? value, IComparer? comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - return BinarySearch(array!, array!.GetLowerBound(0), array.Length, value, comparer); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return BinarySearch(array!, array!.GetLowerBound(0), array.Length, value, comparer); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } // Searches a section of an array for a given element using a binary search @@ -467,7 +468,7 @@ public static int BinarySearch(Array array, int index, int length, object? value { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - int lb = array!.GetLowerBound(0); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + int lb = array!.GetLowerBound(0); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected if (index < lb) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) @@ -552,14 +553,14 @@ public static int BinarySearch(T[] array, T value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - return BinarySearch(array!, 0, array!.Length, value, null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return BinarySearch(array!, 0, array!.Length, value, null); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static int BinarySearch(T[] array, T value, System.Collections.Generic.IComparer? comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - return BinarySearch(array!, 0, array!.Length, value, comparer); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return BinarySearch(array!, 0, array!.Length, value, comparer); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static int BinarySearch(T[] array, int index, int length, T value) @@ -576,7 +577,7 @@ public static int BinarySearch(T[] array, int index, int length, T value, Sys if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); - if (array!.Length - index < length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (array!.Length - index < length) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); return ArraySortHelper.Default.BinarySearch(array, index, length, value, comparer); @@ -594,10 +595,10 @@ public static TOutput[] ConvertAll(TInput[] array, Converter(T[] array, T value) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { array[i] = value; } @@ -661,22 +662,23 @@ public static void Fill(T[] array, T value, int startIndex, int count) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (startIndex < 0 || startIndex > array!.Length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (startIndex < 0 || startIndex > array!.Length) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } - if (count < 0 || startIndex > array!.Length - count) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (count < 0 || startIndex > array!.Length - count) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } for (int i = startIndex; i < startIndex + count; i++) { - array![i] = value; // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + array![i] = value; // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } } + [return: MaybeNull] public static T Find(T[] array, Predicate match) { if (array == null) @@ -689,14 +691,14 @@ public static T Find(T[] array, Predicate match) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { - if (match!(array[i])) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (match!(array[i])) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { return array[i]; } } - return default!; // TODO-NULLABLE-GENERIC + return default!; } public static T[] FindAll(T[] array, Predicate match) @@ -712,9 +714,9 @@ public static T[] FindAll(T[] array, Predicate match) } List list = new List(); - for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { - if (match!(array[i])) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (match!(array[i])) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { list.Add(array[i]); } @@ -729,7 +731,7 @@ public static int FindIndex(T[] array, Predicate match) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - return FindIndex(array!, 0, array!.Length, match); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return FindIndex(array!, 0, array!.Length, match); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static int FindIndex(T[] array, int startIndex, Predicate match) @@ -739,7 +741,7 @@ public static int FindIndex(T[] array, int startIndex, Predicate match) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - return FindIndex(array!, startIndex, array!.Length - startIndex, match); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return FindIndex(array!, startIndex, array!.Length - startIndex, match); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static int FindIndex(T[] array, int startIndex, int count, Predicate match) @@ -749,12 +751,12 @@ public static int FindIndex(T[] array, int startIndex, int count, Predicate array!.Length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (startIndex < 0 || startIndex > array!.Length) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } - if (count < 0 || startIndex > array!.Length - count) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (count < 0 || startIndex > array!.Length - count) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } @@ -767,12 +769,13 @@ public static int FindIndex(T[] array, int startIndex, int count, Predicate(T[] array, Predicate match) { if (array == null) @@ -785,14 +788,14 @@ public static T FindLast(T[] array, Predicate match) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - for (int i = array!.Length - 1; i >= 0; i--) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + for (int i = array!.Length - 1; i >= 0; i--) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { - if (match!(array[i])) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (match!(array[i])) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { return array[i]; } } - return default!; // TODO-NULLABLE-GENERIC + return default!; } public static int FindLastIndex(T[] array, Predicate match) @@ -802,7 +805,7 @@ public static int FindLastIndex(T[] array, Predicate match) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - return FindLastIndex(array!, array!.Length - 1, array.Length, match); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return FindLastIndex(array!, array!.Length - 1, array.Length, match); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static int FindLastIndex(T[] array, int startIndex, Predicate match) @@ -812,7 +815,7 @@ public static int FindLastIndex(T[] array, int startIndex, Predicate match ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - return FindLastIndex(array!, startIndex, startIndex + 1, match); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return FindLastIndex(array!, startIndex, startIndex + 1, match); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static int FindLastIndex(T[] array, int startIndex, int count, Predicate match) @@ -827,7 +830,7 @@ public static int FindLastIndex(T[] array, int startIndex, int count, Predica ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - if (array!.Length == 0) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (array!.Length == 0) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { // Special case for 0 length List if (startIndex != -1) @@ -853,7 +856,7 @@ public static int FindLastIndex(T[] array, int startIndex, int count, Predica int endIndex = startIndex - count; for (int i = startIndex; i > endIndex; i--) { - if (match!(array[i])) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (match!(array[i])) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { return i; } @@ -873,9 +876,9 @@ public static void ForEach(T[] array, Action action) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } - for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { - action!(array[i]); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + action!(array[i]); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } } @@ -887,7 +890,7 @@ public static int IndexOf(Array array, object? value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - return IndexOf(array!, value, array!.GetLowerBound(0), array.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return IndexOf(array!, value, array!.GetLowerBound(0), array.Length); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } // Returns the index of the first occurrence of a given value in a range of @@ -900,7 +903,7 @@ public static int IndexOf(Array array, object? value, int startIndex) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - int lb = array!.GetLowerBound(0); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + int lb = array!.GetLowerBound(0); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected return IndexOf(array, value, startIndex, array.Length - startIndex + lb); } @@ -914,7 +917,7 @@ public static int IndexOf(Array array, object? value, int startIndex, int count) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - if (array!.Rank != 1) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (array!.Rank != 1) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); int lb = array.GetLowerBound(0); @@ -984,7 +987,7 @@ public static int IndexOf(T[] array, T value) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - return IndexOf(array!, value, 0, array!.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return IndexOf(array!, value, 0, array!.Length); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static int IndexOf(T[] array, T value, int startIndex) @@ -994,7 +997,7 @@ public static int IndexOf(T[] array, T value, int startIndex) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - return IndexOf(array!, value, startIndex, array!.Length - startIndex); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return IndexOf(array!, value, startIndex, array!.Length - startIndex); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static int IndexOf(T[] array, T value, int startIndex, int count) @@ -1004,7 +1007,7 @@ public static int IndexOf(T[] array, T value, int startIndex, int count) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if ((uint)startIndex > (uint)array!.Length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if ((uint)startIndex > (uint)array!.Length) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } @@ -1016,24 +1019,40 @@ public static int IndexOf(T[] array, T value, int startIndex, int count) // Hits a code generation bug on ProjectN #if !PROJECTN - if (typeof(T) == typeof(byte)) + if (RuntimeHelpers.IsBitwiseEquatable()) { - int result = SpanHelpers.IndexOf( - ref Unsafe.Add(ref array.GetRawSzArrayData(), startIndex), - Unsafe.As(ref value), - count); - - return (result >= 0 ? startIndex : 0) + result; - } - - if (typeof(T) == typeof(char)) - { - int result = SpanHelpers.IndexOf( - ref Unsafe.Add(ref Unsafe.As(ref array.GetRawSzArrayData()), startIndex), - Unsafe.As(ref value), - count); - - return (result >= 0 ? startIndex : 0) + result; + if (Unsafe.SizeOf() == sizeof(byte)) + { + int result = SpanHelpers.IndexOf( + ref Unsafe.Add(ref array.GetRawSzArrayData(), startIndex), + Unsafe.As(ref value), + count); + return (result >= 0 ? startIndex : 0) + result; + } + else if (Unsafe.SizeOf() == sizeof(char)) + { + int result = SpanHelpers.IndexOf( + ref Unsafe.Add(ref Unsafe.As(ref array.GetRawSzArrayData()), startIndex), + Unsafe.As(ref value), + count); + return (result >= 0 ? startIndex : 0) + result; + } + else if (Unsafe.SizeOf() == sizeof(int)) + { + int result = SpanHelpers.IndexOf( + ref Unsafe.Add(ref Unsafe.As(ref array.GetRawSzArrayData()), startIndex), + Unsafe.As(ref value), + count); + return (result >= 0 ? startIndex : 0) + result; + } + else if (Unsafe.SizeOf() == sizeof(long)) + { + int result = SpanHelpers.IndexOf( + ref Unsafe.Add(ref Unsafe.As(ref array.GetRawSzArrayData()), startIndex), + Unsafe.As(ref value), + count); + return (result >= 0 ? startIndex : 0) + result; + } } #endif @@ -1052,7 +1071,7 @@ public static int LastIndexOf(Array array, object? value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - int lb = array!.GetLowerBound(0); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + int lb = array!.GetLowerBound(0); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected return LastIndexOf(array, value, array.Length - 1 + lb, array.Length); } @@ -1065,7 +1084,7 @@ public static int LastIndexOf(Array array, object? value, int startIndex) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - int lb = array!.GetLowerBound(0); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + int lb = array!.GetLowerBound(0); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected return LastIndexOf(array, value, startIndex, startIndex + 1 - lb); } @@ -1079,7 +1098,7 @@ public static int LastIndexOf(Array array, object? value, int startIndex, int co { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - int lb = array!.GetLowerBound(0); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + int lb = array!.GetLowerBound(0); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected if (array.Length == 0) { return lb - 1; @@ -1151,7 +1170,7 @@ public static int LastIndexOf(T[] array, T value) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - return LastIndexOf(array!, value, array!.Length - 1, array.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return LastIndexOf(array!, value, array!.Length - 1, array.Length); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static int LastIndexOf(T[] array, T value, int startIndex) @@ -1161,7 +1180,7 @@ public static int LastIndexOf(T[] array, T value, int startIndex) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } // if array is empty and startIndex is 0, we need to pass 0 as count - return LastIndexOf(array!, value, startIndex, (array!.Length == 0) ? 0 : (startIndex + 1)); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return LastIndexOf(array!, value, startIndex, (array!.Length == 0) ? 0 : (startIndex + 1)); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static int LastIndexOf(T[] array, T value, int startIndex, int count) @@ -1171,7 +1190,7 @@ public static int LastIndexOf(T[] array, T value, int startIndex, int count) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (array!.Length == 0) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (array!.Length == 0) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { // // Special case for 0 length List @@ -1204,27 +1223,50 @@ public static int LastIndexOf(T[] array, T value, int startIndex, int count) // Hits a code generation bug on ProjectN #if !PROJECTN - if (typeof(T) == typeof(byte)) + if (RuntimeHelpers.IsBitwiseEquatable()) { - int endIndex = startIndex - count + 1; - int result = SpanHelpers.LastIndexOf( - ref Unsafe.Add(ref array.GetRawSzArrayData(), endIndex), - Unsafe.As(ref value), - count); + if (Unsafe.SizeOf() == sizeof(byte)) + { + int endIndex = startIndex - count + 1; + int result = SpanHelpers.LastIndexOf( + ref Unsafe.Add(ref array.GetRawSzArrayData(), endIndex), + Unsafe.As(ref value), + count); - return (result >= 0 ? endIndex : 0) + result; - } + return (result >= 0 ? endIndex : 0) + result; + } + else if (Unsafe.SizeOf() == sizeof(char)) + { + int endIndex = startIndex - count + 1; + int result = SpanHelpers.LastIndexOf( + ref Unsafe.Add(ref Unsafe.As(ref array.GetRawSzArrayData()), endIndex), + Unsafe.As(ref value), + count); - if (typeof(T) == typeof(char)) - { - int endIndex = startIndex - count + 1; - int result = SpanHelpers.LastIndexOf( - ref Unsafe.Add(ref Unsafe.As(ref array.GetRawSzArrayData()), endIndex), - Unsafe.As(ref value), - count); + return (result >= 0 ? endIndex : 0) + result; + } + else if (Unsafe.SizeOf() == sizeof(int)) + { + int endIndex = startIndex - count + 1; + int result = SpanHelpers.LastIndexOf( + ref Unsafe.Add(ref Unsafe.As(ref array.GetRawSzArrayData()), endIndex), + Unsafe.As(ref value), + count); + + return (result >= 0 ? endIndex : 0) + result; + } + else if (Unsafe.SizeOf() == sizeof(long)) + { + int endIndex = startIndex - count + 1; + int result = SpanHelpers.LastIndexOf( + ref Unsafe.Add(ref Unsafe.As(ref array.GetRawSzArrayData()), endIndex), + Unsafe.As(ref value), + count); - return (result >= 0 ? endIndex : 0) + result; + return (result >= 0 ? endIndex : 0) + result; + } } + #endif #if CORECLR @@ -1243,7 +1285,7 @@ public static void Reverse(Array array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Reverse(array!, array!.GetLowerBound(0), array.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + Reverse(array!, array!.GetLowerBound(0), array.Length); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } // Reverses the elements in a range of an array. Following a call to this @@ -1256,7 +1298,7 @@ public static void Reverse(Array array, int index, int length) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - int lowerBound = array!.GetLowerBound(0); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + int lowerBound = array!.GetLowerBound(0); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected if (index < lowerBound) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) @@ -1299,7 +1341,7 @@ public static void Reverse(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Reverse(array!, 0, array!.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + Reverse(array!, 0, array!.Length); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static void Reverse(T[] array, int index, int length) @@ -1310,7 +1352,7 @@ public static void Reverse(T[] array, int index, int length) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); - if (array!.Length - index < length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (array!.Length - index < length) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (length <= 1) @@ -1336,7 +1378,7 @@ public static void Sort(Array array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Sort(array!, null, array!.GetLowerBound(0), array.Length, null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + Sort(array!, null, array!.GetLowerBound(0), array.Length, null); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } // Sorts the elements of two arrays based on the keys in the first array. @@ -1349,7 +1391,7 @@ public static void Sort(Array keys, Array? items) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - Sort(keys!, items, keys!.GetLowerBound(0), keys.Length, null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + Sort(keys!, items, keys!.GetLowerBound(0), keys.Length, null); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } // Sorts the elements in a section of an array. The sort compares the @@ -1397,7 +1439,7 @@ public static void Sort(Array keys, Array? items, IComparer? comparer) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - Sort(keys!, items, keys!.GetLowerBound(0), keys.Length, comparer); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + Sort(keys!, items, keys!.GetLowerBound(0), keys.Length, comparer); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } // Sorts the elements in a section of an array. The sort compares the @@ -1423,7 +1465,7 @@ public static void Sort(Array keys, Array? items, int index, int length, ICompar { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - if (keys!.Rank != 1 || (items != null && items.Rank != 1)) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (keys!.Rank != 1 || (items != null && items.Rank != 1)) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); int keysLowerBound = keys.GetLowerBound(0); if (items != null && keysLowerBound != items.GetLowerBound(0)) @@ -1446,14 +1488,14 @@ public static void Sort(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Sort(array!, 0, array!.Length, null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + Sort(array!, 0, array!.Length, null); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static void Sort(TKey[] keys, TValue[]? items) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - Sort(keys!, items, 0, keys!.Length, null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + Sort(keys!, items, 0, keys!.Length, null); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static void Sort(T[] array, int index, int length) @@ -1470,14 +1512,14 @@ public static void Sort(T[] array, System.Collections.Generic.IComparer? c { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Sort(array!, 0, array!.Length, comparer); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + Sort(array!, 0, array!.Length, comparer); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static void Sort(TKey[] keys, TValue[]? items, System.Collections.Generic.IComparer? comparer) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - Sort(keys!, items, 0, keys!.Length, comparer); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + Sort(keys!, items, 0, keys!.Length, comparer); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static void Sort(T[] array, int index, int length, System.Collections.Generic.IComparer? comparer) @@ -1488,7 +1530,7 @@ public static void Sort(T[] array, int index, int length, System.Collections. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); - if (array!.Length - index < length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (array!.Length - index < length) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (length > 1) @@ -1515,7 +1557,7 @@ public static void Sort(TKey[] keys, TValue[]? items, int index, i ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); - if (keys!.Length - index < length || (items != null && index > items.Length - length)) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (keys!.Length - index < length || (items != null && index > items.Length - length)) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (length > 1) @@ -1552,7 +1594,7 @@ public static void Sort(T[] array, Comparison comparison) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } - ArraySortHelper.Sort(array!, 0, array!.Length, comparison); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + ArraySortHelper.Sort(array!, 0, array!.Length, comparison!); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static bool TrueForAll(T[] array, Predicate match) @@ -1567,9 +1609,9 @@ public static bool TrueForAll(T[] array, Predicate match) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { - if (!match!(array[i])) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (!match!(array[i])) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { return false; } diff --git a/src/Common/src/CoreLib/System/ArraySegment.cs b/src/Common/src/CoreLib/System/ArraySegment.cs index 58eb506f67d6..0f6e05f892a2 100644 --- a/src/Common/src/CoreLib/System/ArraySegment.cs +++ b/src/Common/src/CoreLib/System/ArraySegment.cs @@ -13,7 +13,6 @@ ** ===========================================================*/ -#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; @@ -44,7 +43,7 @@ public ArraySegment(T[] array) _array = array; _offset = 0; - _count = array!.Length; // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + _count = array!.Length; // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public ArraySegment(T[] array, int offset, int count) @@ -324,7 +323,7 @@ internal Enumerator(ArraySegment arraySegment) Debug.Assert(arraySegment.Array != null); Debug.Assert(arraySegment.Offset >= 0); Debug.Assert(arraySegment.Count >= 0); - Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array!.Length); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34792 + Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array!.Length); // TODO-NULLABLE: Manually-implemented property (https://github.com/dotnet/roslyn/issues/34792) _array = arraySegment.Array; _start = arraySegment.Offset; diff --git a/src/Common/src/CoreLib/System/ArrayTypeMismatchException.cs b/src/Common/src/CoreLib/System/ArrayTypeMismatchException.cs index c2a6244e5019..263b69e636cd 100644 --- a/src/Common/src/CoreLib/System/ArrayTypeMismatchException.cs +++ b/src/Common/src/CoreLib/System/ArrayTypeMismatchException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/AssemblyLoadEventArgs.cs b/src/Common/src/CoreLib/System/AssemblyLoadEventArgs.cs index 43b32d74cfd5..d7e524969330 100644 --- a/src/Common/src/CoreLib/System/AssemblyLoadEventArgs.cs +++ b/src/Common/src/CoreLib/System/AssemblyLoadEventArgs.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Reflection; namespace System diff --git a/src/Common/src/CoreLib/System/AssemblyLoadEventHandler.cs b/src/Common/src/CoreLib/System/AssemblyLoadEventHandler.cs index af89e634b33a..0d5a2823c919 100644 --- a/src/Common/src/CoreLib/System/AssemblyLoadEventHandler.cs +++ b/src/Common/src/CoreLib/System/AssemblyLoadEventHandler.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { public delegate void AssemblyLoadEventHandler(object? sender, AssemblyLoadEventArgs args); diff --git a/src/Common/src/CoreLib/System/AsyncCallback.cs b/src/Common/src/CoreLib/System/AsyncCallback.cs index f06749f60b21..036d44a4b97d 100644 --- a/src/Common/src/CoreLib/System/AsyncCallback.cs +++ b/src/Common/src/CoreLib/System/AsyncCallback.cs @@ -10,7 +10,6 @@ ** ===========================================================*/ -#nullable enable namespace System { public delegate void AsyncCallback(IAsyncResult ar); diff --git a/src/Common/src/CoreLib/System/Attribute.cs b/src/Common/src/CoreLib/System/Attribute.cs index 755d7722615c..e24797563cff 100644 --- a/src/Common/src/CoreLib/System/Attribute.cs +++ b/src/Common/src/CoreLib/System/Attribute.cs @@ -15,7 +15,7 @@ public abstract partial class Attribute protected Attribute() { } #if !CORERT - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj == null) return false; @@ -25,7 +25,7 @@ public override bool Equals(object obj) Type thisType = this.GetType(); object thisObj = this; - object thisResult, thatResult; + object? thisResult, thatResult; while (thisType != typeof(Attribute)) { @@ -41,7 +41,7 @@ public override bool Equals(object obj) return false; } } - thisType = thisType.BaseType; + thisType = thisType.BaseType!; } return true; @@ -54,11 +54,11 @@ public override int GetHashCode() while (type != typeof(Attribute)) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); - object vThis = null; + object? vThis = null; for (int i = 0; i < fields.Length; i++) { - object fieldValue = fields[i].GetValue(this); + object? fieldValue = fields[i].GetValue(this); // The hashcode of an array ignores the contents of the array, so it can produce // different hashcodes for arrays with the same contents. @@ -74,7 +74,7 @@ public override int GetHashCode() if (vThis != null) return vThis.GetHashCode(); - type = type.BaseType; + type = type.BaseType!; } return type.GetHashCode(); @@ -82,7 +82,7 @@ public override int GetHashCode() #endif // Compares values of custom-attribute fields. - private static bool AreFieldValuesEqual(object thisValue, object thatValue) + private static bool AreFieldValuesEqual(object? thisValue, object? thatValue) { if (thisValue == null && thatValue == null) return true; @@ -99,8 +99,8 @@ private static bool AreFieldValuesEqual(object thisValue, object thatValue) return false; } - Array thisValueArray = thisValue as Array; - Array thatValueArray = thatValue as Array; + Array thisValueArray = (Array)thisValue; + Array thatValueArray = (Array)thatValue; if (thisValueArray.Length != thatValueArray.Length) { return false; @@ -132,7 +132,7 @@ private static bool AreFieldValuesEqual(object thisValue, object thatValue) public virtual object TypeId => GetType(); - public virtual bool Match(object obj) => Equals(obj); + public virtual bool Match(object? obj) => Equals(obj); public virtual bool IsDefaultAttribute() => false; } diff --git a/src/Common/src/CoreLib/System/AttributeTargets.cs b/src/Common/src/CoreLib/System/AttributeTargets.cs index dbbade3a600e..c33d19e85ea3 100644 --- a/src/Common/src/CoreLib/System/AttributeTargets.cs +++ b/src/Common/src/CoreLib/System/AttributeTargets.cs @@ -5,7 +5,6 @@ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -#nullable enable namespace System { // Enum used to indicate all the elements of the diff --git a/src/Common/src/CoreLib/System/AttributeUsageAttribute.cs b/src/Common/src/CoreLib/System/AttributeUsageAttribute.cs index d96e4057cc36..8a4a0a661bf6 100644 --- a/src/Common/src/CoreLib/System/AttributeUsageAttribute.cs +++ b/src/Common/src/CoreLib/System/AttributeUsageAttribute.cs @@ -11,7 +11,6 @@ ** ===========================================================*/ -#nullable enable using System.Reflection; namespace System diff --git a/src/Common/src/CoreLib/System/BadImageFormatException.cs b/src/Common/src/CoreLib/System/BadImageFormatException.cs index 183923193268..23aa56453bc6 100644 --- a/src/Common/src/CoreLib/System/BadImageFormatException.cs +++ b/src/Common/src/CoreLib/System/BadImageFormatException.cs @@ -11,7 +11,6 @@ ** ===========================================================*/ -#nullable enable using System.Globalization; using System.IO; using System.Runtime.Serialization; diff --git a/src/Common/src/CoreLib/System/BitConverter.cs b/src/Common/src/CoreLib/System/BitConverter.cs index 196725ecebdb..f6f6b983795c 100644 --- a/src/Common/src/CoreLib/System/BitConverter.cs +++ b/src/Common/src/CoreLib/System/BitConverter.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -237,7 +236,7 @@ public static short ToInt16(byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - if (unchecked((uint)startIndex) >= unchecked((uint)value!.Length)) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (unchecked((uint)startIndex) >= unchecked((uint)value!.Length)) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - sizeof(short)) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); @@ -258,7 +257,7 @@ public static int ToInt32(byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - if (unchecked((uint)startIndex) >= unchecked((uint)value!.Length)) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (unchecked((uint)startIndex) >= unchecked((uint)value!.Length)) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - sizeof(int)) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); @@ -279,7 +278,7 @@ public static long ToInt64(byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - if (unchecked((uint)startIndex) >= unchecked((uint)value!.Length)) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (unchecked((uint)startIndex) >= unchecked((uint)value!.Length)) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - sizeof(long)) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); @@ -364,11 +363,11 @@ public static string ToString(byte[] value, int startIndex, int length) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - if (startIndex < 0 || startIndex >= value!.Length && startIndex > 0) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (startIndex < 0 || startIndex >= value!.Length && startIndex > 0) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_GenericPositive); - if (startIndex > value!.Length - length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (startIndex > value!.Length - length) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); if (length == 0) @@ -410,7 +409,7 @@ public static string ToString(byte[] value) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - return ToString(value!, 0, value!.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return ToString(value!, 0, value!.Length); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } // Converts an array of bytes into a String. @@ -418,7 +417,7 @@ public static string ToString(byte[] value, int startIndex) { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - return ToString(value!, startIndex, value!.Length - startIndex); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return ToString(value!, startIndex, value!.Length - startIndex); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } /*==================================ToBoolean=================================== @@ -436,7 +435,7 @@ public static bool ToBoolean(byte[] value, int startIndex) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if (startIndex < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); - if (startIndex > value!.Length - 1) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (startIndex > value!.Length - 1) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); // differs from other overloads, which throw base ArgumentException return value[startIndex] != 0; diff --git a/src/Common/src/CoreLib/System/Boolean.cs b/src/Common/src/CoreLib/System/Boolean.cs index 33e11be0dcdf..a7ac01cd2e06 100644 --- a/src/Common/src/CoreLib/System/Boolean.cs +++ b/src/Common/src/CoreLib/System/Boolean.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ -#nullable enable using System.Runtime.CompilerServices; using System.Runtime.Versioning; diff --git a/src/Common/src/CoreLib/System/Buffer.Unix.cs b/src/Common/src/CoreLib/System/Buffer.Unix.cs index 7de47fd6a21c..372cf92557d9 100644 --- a/src/Common/src/CoreLib/System/Buffer.Unix.cs +++ b/src/Common/src/CoreLib/System/Buffer.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable #if BIT64 using nuint = System.UInt64; #else diff --git a/src/Common/src/CoreLib/System/Buffer.Windows.cs b/src/Common/src/CoreLib/System/Buffer.Windows.cs index 2609e90ad997..ccb577a7e1b6 100644 --- a/src/Common/src/CoreLib/System/Buffer.Windows.cs +++ b/src/Common/src/CoreLib/System/Buffer.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable #if BIT64 using nuint = System.UInt64; #else diff --git a/src/Common/src/CoreLib/System/Buffer.cs b/src/Common/src/CoreLib/System/Buffer.cs index da62bc50b47b..f2ffaaea85dc 100644 --- a/src/Common/src/CoreLib/System/Buffer.cs +++ b/src/Common/src/CoreLib/System/Buffer.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable #if AMD64 || ARM64 || (BIT32 && !ARM) #define HAS_CUSTOM_BLOCKS #endif diff --git a/src/Common/src/CoreLib/System/Buffers/ArrayPool.cs b/src/Common/src/CoreLib/System/Buffers/ArrayPool.cs index 8e67e2259972..5e01399a3330 100644 --- a/src/Common/src/CoreLib/System/Buffers/ArrayPool.cs +++ b/src/Common/src/CoreLib/System/Buffers/ArrayPool.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers { /// diff --git a/src/Common/src/CoreLib/System/Buffers/ArrayPoolEventSource.cs b/src/Common/src/CoreLib/System/Buffers/ArrayPoolEventSource.cs index 9ae0e3d913eb..d0563c4977d8 100644 --- a/src/Common/src/CoreLib/System/Buffers/ArrayPoolEventSource.cs +++ b/src/Common/src/CoreLib/System/Buffers/ArrayPoolEventSource.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics.Tracing; namespace System.Buffers diff --git a/src/Common/src/CoreLib/System/Buffers/Binary/Reader.cs b/src/Common/src/CoreLib/System/Buffers/Binary/Reader.cs index f4a8142731f4..49d0a2db4218 100644 --- a/src/Common/src/CoreLib/System/Buffers/Binary/Reader.cs +++ b/src/Common/src/CoreLib/System/Buffers/Binary/Reader.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Numerics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/Buffers/Binary/ReaderBigEndian.cs b/src/Common/src/CoreLib/System/Buffers/Binary/ReaderBigEndian.cs index 31745dd3cc46..b45dd8913d34 100644 --- a/src/Common/src/CoreLib/System/Buffers/Binary/ReaderBigEndian.cs +++ b/src/Common/src/CoreLib/System/Buffers/Binary/ReaderBigEndian.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/Buffers/Binary/ReaderLittleEndian.cs b/src/Common/src/CoreLib/System/Buffers/Binary/ReaderLittleEndian.cs index e4a03c013a42..bd832f8995aa 100644 --- a/src/Common/src/CoreLib/System/Buffers/Binary/ReaderLittleEndian.cs +++ b/src/Common/src/CoreLib/System/Buffers/Binary/ReaderLittleEndian.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/Buffers/Binary/WriterBigEndian.cs b/src/Common/src/CoreLib/System/Buffers/Binary/WriterBigEndian.cs index ea56c78a4b36..78be9b5a0356 100644 --- a/src/Common/src/CoreLib/System/Buffers/Binary/WriterBigEndian.cs +++ b/src/Common/src/CoreLib/System/Buffers/Binary/WriterBigEndian.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/Buffers/Binary/WriterLittleEndian.cs b/src/Common/src/CoreLib/System/Buffers/Binary/WriterLittleEndian.cs index 201ead0e9fb1..5d63ee5f0b43 100644 --- a/src/Common/src/CoreLib/System/Buffers/Binary/WriterLittleEndian.cs +++ b/src/Common/src/CoreLib/System/Buffers/Binary/WriterLittleEndian.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/Buffers/ConfigurableArrayPool.cs b/src/Common/src/CoreLib/System/Buffers/ConfigurableArrayPool.cs index dd49d8a2501b..6dd306325819 100644 --- a/src/Common/src/CoreLib/System/Buffers/ConfigurableArrayPool.cs +++ b/src/Common/src/CoreLib/System/Buffers/ConfigurableArrayPool.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Threading; diff --git a/src/Common/src/CoreLib/System/Buffers/IMemoryOwner.cs b/src/Common/src/CoreLib/System/Buffers/IMemoryOwner.cs index 19d01166c640..44f16c58273f 100644 --- a/src/Common/src/CoreLib/System/Buffers/IMemoryOwner.cs +++ b/src/Common/src/CoreLib/System/Buffers/IMemoryOwner.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers { /// diff --git a/src/Common/src/CoreLib/System/Buffers/IPinnable.cs b/src/Common/src/CoreLib/System/Buffers/IPinnable.cs index b8b49d4cd12d..623e716a053c 100644 --- a/src/Common/src/CoreLib/System/Buffers/IPinnable.cs +++ b/src/Common/src/CoreLib/System/Buffers/IPinnable.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers { /// diff --git a/src/Common/src/CoreLib/System/Buffers/MemoryHandle.cs b/src/Common/src/CoreLib/System/Buffers/MemoryHandle.cs index 23325d5d6e86..9cefbc9158a0 100644 --- a/src/Common/src/CoreLib/System/Buffers/MemoryHandle.cs +++ b/src/Common/src/CoreLib/System/Buffers/MemoryHandle.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; namespace System.Buffers diff --git a/src/Common/src/CoreLib/System/Buffers/MemoryManager.cs b/src/Common/src/CoreLib/System/Buffers/MemoryManager.cs index 5c4061e9b4bd..1b235b538e47 100644 --- a/src/Common/src/CoreLib/System/Buffers/MemoryManager.cs +++ b/src/Common/src/CoreLib/System/Buffers/MemoryManager.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; namespace System.Buffers diff --git a/src/Common/src/CoreLib/System/Buffers/OperationStatus.cs b/src/Common/src/CoreLib/System/Buffers/OperationStatus.cs index c8235f7cc49e..e9ddcab57148 100644 --- a/src/Common/src/CoreLib/System/Buffers/OperationStatus.cs +++ b/src/Common/src/CoreLib/System/Buffers/OperationStatus.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers { /// diff --git a/src/Common/src/CoreLib/System/Buffers/StandardFormat.cs b/src/Common/src/CoreLib/System/Buffers/StandardFormat.cs index 5675f4ced34a..24a49838308d 100644 --- a/src/Common/src/CoreLib/System/Buffers/StandardFormat.cs +++ b/src/Common/src/CoreLib/System/Buffers/StandardFormat.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Buffers diff --git a/src/Common/src/CoreLib/System/Buffers/Text/FormattingHelpers.CountDigits.cs b/src/Common/src/CoreLib/System/Buffers/Text/FormattingHelpers.CountDigits.cs index a7a1fc24a826..ac45347a5edb 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/FormattingHelpers.CountDigits.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/FormattingHelpers.CountDigits.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Constants.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Constants.cs index 25880fcf95ca..e2f70f0b10e9 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Constants.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Constants.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { internal static partial class Utf8Constants diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/FormattingHelpers.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/FormattingHelpers.cs index a9f185aae927..1b30d5f01336 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/FormattingHelpers.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/FormattingHelpers.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Boolean.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Boolean.cs index bc6b894be7a1..31bb6cae5559 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Boolean.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Boolean.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers.Binary; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.G.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.G.cs index 2290a107268d..7c4a2e342d89 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.G.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.G.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Formatter diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.L.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.L.cs index e817064bf8d1..699f91f39c8d 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.L.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.L.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Formatter diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.O.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.O.cs index 706c634dddad..d9b7b181bc44 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.O.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.O.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Formatter diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.R.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.R.cs index aed0795b39d7..dd9ec459b7b8 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.R.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.R.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Formatter diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.cs index 31da577c822e..046885d16270 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Date.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Formatter diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.E.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.E.cs index 859adea1ca9f..89b54f2fd59d 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.E.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.E.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.F.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.F.cs index 1efe257f541f..51bc20b8d2d1 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.F.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.F.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.G.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.G.cs index c73774939470..b867eaec1a1d 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.G.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.G.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.cs index 72b9fca51bf0..bb93b992efb9 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Decimal.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Float.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Float.cs index c4d70b4da981..96e70bada945 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Float.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Float.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Globalization; using System.Text; diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Guid.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Guid.cs index 61085b892480..479f1dd1cb19 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Guid.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Guid.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.D.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.D.cs index 88f4c1602844..7532f0cf15ad 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.D.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.D.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.Default.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.Default.cs index 1c213e38795d..046f5baf6644 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.Default.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.Default.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.N.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.N.cs index 542bd1eeb79c..1c01b8d60d4b 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.N.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.N.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.cs index 025fc8b45ec8..fcd20b312d79 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Signed.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.D.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.D.cs index 78542eb4cfb6..9cb8d64bc0c0 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.D.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.D.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { /// diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.Default.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.Default.cs index 5d8f1f01180c..d83591ed980e 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.Default.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.Default.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.N.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.N.cs index b6caaa6cf923..ce21c0d3ddd6 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.N.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.N.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { /// diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.X.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.X.cs index 1db31dfe5925..4cf4d52b5c87 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.X.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.X.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { /// diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.cs index b531ba714d58..0040c5075a65 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.Unsigned.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.cs index 2024551ff971..3b83fb75125f 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.Integer.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { /// diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.TimeSpan.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.TimeSpan.cs index b41cb75d0ef2..38bb35f7dfa6 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.TimeSpan.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Formatter/Utf8Formatter.TimeSpan.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/ParserHelpers.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/ParserHelpers.cs index 7630277464fd..1bdb01347182 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/ParserHelpers.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/ParserHelpers.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Boolean.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Boolean.cs index 56d88e9d4679..3b039bae2509 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Boolean.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Boolean.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers.Binary; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.Default.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.Default.cs index 4df370337d0a..77d7e1224bee 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.Default.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.Default.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Parser diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.G.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.G.cs index d930831b60c5..6e8edbcbdf85 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.G.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.G.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Parser diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.Helpers.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.Helpers.cs index 0d62d818830c..d2fb06829a6f 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.Helpers.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.Helpers.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.O.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.O.cs index 9ea3fa34f195..8d2c681f68e1 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.O.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.O.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.R.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.R.cs index 7a16b07e181a..316bee01b424 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.R.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.R.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Parser diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.cs index 37070ef5cf71..35ad71670595 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Date.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Decimal.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Decimal.cs index 84bc7797deb6..5ed385a71be9 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Decimal.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Decimal.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Parser diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Float.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Float.cs index c2f84dd2b45b..27780397e327 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Float.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Float.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers.Binary; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Guid.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Guid.cs index 18aaf64212da..f0a99dd522f6 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Guid.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Guid.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Parser diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Signed.D.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Signed.D.cs index fc9eb5ea25a0..bf1871a1c94a 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Signed.D.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Signed.D.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Parser diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Signed.N.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Signed.N.cs index 8cf986b18ee8..fd8ce572f271 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Signed.N.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Signed.N.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Parser diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Signed.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Signed.cs index 0ee5b7e3f96c..2e861b1cfdd9 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Signed.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Signed.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Internal.Runtime.CompilerServices; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.D.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.D.cs index 675231b26f43..46753f5c57d1 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.D.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.D.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Parser diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.N.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.N.cs index 72f2831e6219..2db20c127011 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.N.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.N.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { // diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.X.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.X.cs index 1042faece2f8..7e7867a56fd3 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.X.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.X.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Parser diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.cs index f420bf1818de..7c4e94e56f12 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Integer.Unsigned.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Parser diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Number.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Number.cs index 2727747d34bf..799a3fe6a741 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Number.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.Number.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.BigG.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.BigG.cs index e05523c45f92..6bcb4d527778 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.BigG.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.BigG.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Parser diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.C.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.C.cs index 94d539fa888a..d0a28969be8d 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.C.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.C.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Parser diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.LittleG.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.LittleG.cs index 7172da4e0c52..19208b9eaced 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.LittleG.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.LittleG.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Buffers.Text { public static partial class Utf8Parser diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.cs index 641a0b3f0302..b49cccb6a2f5 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpan.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpanSplitter.cs b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpanSplitter.cs index 4340399ec9b8..0c72d1f3a2d3 100644 --- a/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpanSplitter.cs +++ b/src/Common/src/CoreLib/System/Buffers/Text/Utf8Parser/Utf8Parser.TimeSpanSplitter.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Buffers.Text diff --git a/src/Common/src/CoreLib/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs b/src/Common/src/CoreLib/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs index 59e109a0431c..47470715ecf5 100644 --- a/src/Common/src/CoreLib/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs +++ b/src/Common/src/CoreLib/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; @@ -247,7 +246,7 @@ public bool Trim() // Under high pressure, release all thread locals if (log.IsEnabled()) { - foreach (KeyValuePair tlsBuckets in s_allTlsBuckets) + foreach (KeyValuePair tlsBuckets in s_allTlsBuckets) { T[]?[] buckets = tlsBuckets.Key; for (int i = 0; i < buckets.Length; i++) diff --git a/src/Common/src/CoreLib/System/Buffers/Utilities.cs b/src/Common/src/CoreLib/System/Buffers/Utilities.cs index c49555a6e531..7e1caa039b36 100644 --- a/src/Common/src/CoreLib/System/Buffers/Utilities.cs +++ b/src/Common/src/CoreLib/System/Buffers/Utilities.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/ByReference.cs b/src/Common/src/CoreLib/System/ByReference.cs index bb75753f5be4..5da3c99f41b1 100644 --- a/src/Common/src/CoreLib/System/ByReference.cs +++ b/src/Common/src/CoreLib/System/ByReference.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; using System.Runtime.Versioning; diff --git a/src/Common/src/CoreLib/System/Byte.cs b/src/Common/src/CoreLib/System/Byte.cs index de3eb7a7db0b..5370fec690e0 100644 --- a/src/Common/src/CoreLib/System/Byte.cs +++ b/src/Common/src/CoreLib/System/Byte.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/CLSCompliantAttribute.cs b/src/Common/src/CoreLib/System/CLSCompliantAttribute.cs index 9790e935f34e..d895b5ac7166 100644 --- a/src/Common/src/CoreLib/System/CLSCompliantAttribute.cs +++ b/src/Common/src/CoreLib/System/CLSCompliantAttribute.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable namespace System { [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] diff --git a/src/Common/src/CoreLib/System/CannotUnloadAppDomainException.cs b/src/Common/src/CoreLib/System/CannotUnloadAppDomainException.cs index 450a54c96b3a..6d68f08c5c52 100644 --- a/src/Common/src/CoreLib/System/CannotUnloadAppDomainException.cs +++ b/src/Common/src/CoreLib/System/CannotUnloadAppDomainException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/Char.cs b/src/Common/src/CoreLib/System/Char.cs index 80dce56258b7..3835f8e99600 100644 --- a/src/Common/src/CoreLib/System/Char.cs +++ b/src/Common/src/CoreLib/System/Char.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ -#nullable enable using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/CharEnumerator.cs b/src/Common/src/CoreLib/System/CharEnumerator.cs index 0b2caefdfa32..1e775380805d 100644 --- a/src/Common/src/CoreLib/System/CharEnumerator.cs +++ b/src/Common/src/CoreLib/System/CharEnumerator.cs @@ -12,7 +12,6 @@ ** ============================================================*/ -#nullable enable using System.Collections; using System.Collections.Generic; @@ -55,7 +54,7 @@ public void Dispose() _str = null; } - object? IEnumerator.Current // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 + object? IEnumerator.Current { get { return Current; } } diff --git a/src/Common/src/CoreLib/System/Collections/ArrayList.cs b/src/Common/src/CoreLib/System/Collections/ArrayList.cs index d2ccc23d70a3..ba4a323c4eb9 100644 --- a/src/Common/src/CoreLib/System/Collections/ArrayList.cs +++ b/src/Common/src/CoreLib/System/Collections/ArrayList.cs @@ -33,7 +33,7 @@ namespace System.Collections #endif public class ArrayList : IList, ICloneable { - private object[] _items; // Do not rename (binary serialization) + private object?[] _items = null!; // Do not rename (binary serialization) private int _size; // Do not rename (binary serialization) private int _version; // Do not rename (binary serialization) @@ -161,7 +161,7 @@ public virtual bool IsSynchronized // Sets or Gets the element at the given index. // - public virtual object this[int index] + public virtual object? this[int index] { get { @@ -195,7 +195,7 @@ public static ArrayList Adapter(IList list) // increased by one. If required, the capacity of the list is doubled // before adding the new element. // - public virtual int Add(object value) + public virtual int Add(object? value) { if (_size == _items.Length) EnsureCapacity(_size + 1); _items[_size] = value; @@ -232,7 +232,7 @@ public virtual void AddRange(ICollection c) // The method uses the Array.BinarySearch method to perform the // search. // - public virtual int BinarySearch(int index, int count, object value, IComparer comparer) + public virtual int BinarySearch(int index, int count, object? value, IComparer? comparer) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -244,12 +244,12 @@ public virtual int BinarySearch(int index, int count, object value, IComparer co return Array.BinarySearch((Array)_items, index, count, value, comparer); } - public virtual int BinarySearch(object value) + public virtual int BinarySearch(object? value) { return BinarySearch(0, Count, value, null); } - public virtual int BinarySearch(object value, IComparer comparer) + public virtual int BinarySearch(object? value, IComparer? comparer) { return BinarySearch(0, Count, value, comparer); } @@ -283,7 +283,7 @@ public virtual object Clone() // It does a linear, O(n) search. Equality is determined by calling // item.Equals(). // - public virtual bool Contains(object item) + public virtual bool Contains(object? item) { if (item == null) { @@ -295,7 +295,7 @@ public virtual bool Contains(object item) else { for (int i = 0; i < _size; i++) - if ((_items[i] != null) && (_items[i].Equals(item))) + if ((_items[i] != null) && (_items[i]!.Equals(item))) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) return true; return false; } @@ -318,7 +318,7 @@ public virtual void CopyTo(Array array, int arrayIndex) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); // Delegate rest of error checking to Array.Copy. - Array.Copy(_items, 0, array, arrayIndex, _size); + Array.Copy(_items, 0, array!, arrayIndex, _size); } // Copies a section of this list to the given array at the given index. @@ -333,7 +333,7 @@ public virtual void CopyTo(int index, Array array, int arrayIndex, int count) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); // Delegate rest of error checking to Array.Copy. - Array.Copy(_items, index, array, arrayIndex, count); + Array.Copy(_items, index, array!, arrayIndex, count); } // Ensures that the capacity of this list is at least the given minimum @@ -407,7 +407,7 @@ public virtual IEnumerator GetEnumerator(int index, int count) // This method uses the Array.IndexOf method to perform the // search. // - public virtual int IndexOf(object value) + public virtual int IndexOf(object? value) { return Array.IndexOf((Array)_items, value, 0, _size); } @@ -421,7 +421,7 @@ public virtual int IndexOf(object value) // This method uses the Array.IndexOf method to perform the // search. // - public virtual int IndexOf(object value, int startIndex) + public virtual int IndexOf(object? value, int startIndex) { if (startIndex > _size) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); @@ -437,7 +437,7 @@ public virtual int IndexOf(object value, int startIndex) // This method uses the Array.IndexOf method to perform the // search. // - public virtual int IndexOf(object value, int startIndex, int count) + public virtual int IndexOf(object? value, int startIndex, int count) { if (startIndex > _size) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); @@ -449,7 +449,7 @@ public virtual int IndexOf(object value, int startIndex, int count) // is increased by one. If required, the capacity of the list is doubled // before inserting the new element. // - public virtual void Insert(int index, object value) + public virtual void Insert(int index, object? value) { // Note that insertions at the end are legal. if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); @@ -501,7 +501,7 @@ public virtual void InsertRange(int index, ICollection c) // This method uses the Array.LastIndexOf method to perform the // search. // - public virtual int LastIndexOf(object value) + public virtual int LastIndexOf(object? value) { return LastIndexOf(value, _size - 1, _size); } @@ -515,7 +515,7 @@ public virtual int LastIndexOf(object value) // This method uses the Array.LastIndexOf method to perform the // search. // - public virtual int LastIndexOf(object value, int startIndex) + public virtual int LastIndexOf(object? value, int startIndex) { if (startIndex >= _size) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); @@ -531,7 +531,7 @@ public virtual int LastIndexOf(object value, int startIndex) // This method uses the Array.LastIndexOf method to perform the // search. // - public virtual int LastIndexOf(object value, int startIndex, int count) + public virtual int LastIndexOf(object? value, int startIndex, int count) { if (Count != 0 && (startIndex < 0 || count < 0)) throw new ArgumentOutOfRangeException(startIndex < 0 ? nameof(startIndex) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -566,7 +566,7 @@ public static ArrayList ReadOnly(ArrayList list) // Removes the element at the given index. The size of the list is // decreased by one. // - public virtual void Remove(object obj) + public virtual void Remove(object? obj) { int index = IndexOf(obj); if (index >= 0) @@ -615,7 +615,7 @@ public virtual void RemoveRange(int index, int count) // Returns an IList that contains count copies of value. // - public static ArrayList Repeat(object value, int count) + public static ArrayList Repeat(object? value, int count) { if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -688,7 +688,7 @@ public virtual void Sort() // Sorts the elements in this list. Uses Array.Sort with the // provided comparer. - public virtual void Sort(IComparer comparer) + public virtual void Sort(IComparer? comparer) { Sort(0, Count, comparer); } @@ -701,7 +701,7 @@ public virtual void Sort(IComparer comparer) // // This method uses the Array.Sort method to sort the elements. // - public virtual void Sort(int index, int count, IComparer comparer) + public virtual void Sort(int index, int count, IComparer? comparer) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -734,12 +734,12 @@ public static ArrayList Synchronized(ArrayList list) // ToArray returns a new Object array containing the contents of the ArrayList. // This requires copying the ArrayList, which is an O(n) operation. - public virtual object[] ToArray() + public virtual object?[] ToArray() { if (_size == 0) return Array.Empty(); - object[] array = new object[_size]; + object?[] array = new object[_size]; Array.Copy(_items, 0, array, 0, _size); return array; } @@ -816,7 +816,7 @@ public override bool IsSynchronized get { return _list.IsSynchronized; } } - public override object this[int index] + public override object? this[int index] { get { @@ -834,7 +834,7 @@ public override object SyncRoot get { return _list.SyncRoot; } } - public override int Add(object obj) + public override int Add(object? obj) { int i = _list.Add(obj); _version++; @@ -847,7 +847,7 @@ public override void AddRange(ICollection c) } // Other overloads with automatically work - public override int BinarySearch(int index, int count, object value, IComparer comparer) + public override int BinarySearch(int index, int count, object? value, IComparer? comparer) { if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -896,7 +896,7 @@ public override object Clone() return new IListWrapper(_list); } - public override bool Contains(object obj) + public override bool Contains(object? obj) { return _list.Contains(obj); } @@ -942,18 +942,18 @@ public override IEnumerator GetEnumerator(int index, int count) return new IListWrapperEnumWrapper(this, index, count); } - public override int IndexOf(object value) + public override int IndexOf(object? value) { return _list.IndexOf(value); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int IndexOf(object value, int startIndex) + public override int IndexOf(object? value, int startIndex) { return IndexOf(value, startIndex, _list.Count - startIndex); } - public override int IndexOf(object value, int startIndex, int count) + public override int IndexOf(object? value, int startIndex, int count) { if (startIndex < 0 || startIndex > Count) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || startIndex > Count - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); @@ -969,13 +969,13 @@ public override int IndexOf(object value, int startIndex, int count) else { for (int i = startIndex; i < endIndex; i++) - if (_list[i] != null && _list[i].Equals(value)) + if (_list[i] != null && _list[i]!.Equals(value)) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) return i; return -1; } } - public override void Insert(int index, object obj) + public override void Insert(int index, object? obj) { _list.Insert(index, obj); _version++; @@ -989,7 +989,7 @@ public override void InsertRange(int index, ICollection c) if (c.Count > 0) { - ArrayList al = _list as ArrayList; + ArrayList? al = _list as ArrayList; if (al != null) { // We need to special case ArrayList. @@ -1009,19 +1009,19 @@ public override void InsertRange(int index, ICollection c) } } - public override int LastIndexOf(object value) + public override int LastIndexOf(object? value) { return LastIndexOf(value, _list.Count - 1, _list.Count); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int LastIndexOf(object value, int startIndex) + public override int LastIndexOf(object? value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int LastIndexOf(object value, int startIndex, int count) + public override int LastIndexOf(object? value, int startIndex, int count) { if (_list.Count == 0) return -1; @@ -1040,13 +1040,13 @@ public override int LastIndexOf(object value, int startIndex, int count) else { for (int i = startIndex; i >= endIndex; i--) - if (_list[i] != null && _list[i].Equals(value)) + if (_list[i] != null && _list[i]!.Equals(value)) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) return i; return -1; } } - public override void Remove(object value) + public override void Remove(object? value) { int index = IndexOf(value); if (index >= 0) @@ -1089,7 +1089,7 @@ public override void Reverse(int index, int count) int j = index + count - 1; while (i < j) { - object tmp = _list[i]; + object? tmp = _list[i]; _list[i++] = _list[j]; _list[j--] = tmp; } @@ -1128,7 +1128,7 @@ public override ArrayList GetRange(int index, int count) return new Range(this, index, count); } - public override void Sort(int index, int count, IComparer comparer) + public override void Sort(int index, int count, IComparer? comparer) { if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -1145,12 +1145,12 @@ public override void Sort(int index, int count, IComparer comparer) } - public override object[] ToArray() + public override object?[] ToArray() { if (Count == 0) - return Array.Empty(); + return Array.Empty(); - object[] array = new object[Count]; + object?[] array = new object[Count]; _list.CopyTo(array, 0); return array; } @@ -1174,7 +1174,7 @@ public override void TrimToSize() // class that implements all of ArrayList's methods. private sealed class IListWrapperEnumWrapper : IEnumerator, ICloneable { - private IEnumerator _en; + private IEnumerator _en = null!; private int _remaining; private int _initialStartIndex; // for reset private int _initialCount; // for reset @@ -1216,7 +1216,7 @@ public bool MoveNext() return r && _remaining-- > 0; } - public object Current + public object? Current { get { @@ -1291,7 +1291,7 @@ public override bool IsSynchronized get { return true; } } - public override object this[int index] + public override object? this[int index] { get { @@ -1314,7 +1314,7 @@ public override object SyncRoot get { return _root; } } - public override int Add(object value) + public override int Add(object? value) { lock (_root) { @@ -1330,7 +1330,7 @@ public override void AddRange(ICollection c) } } - public override int BinarySearch(object value) + public override int BinarySearch(object? value) { lock (_root) { @@ -1338,7 +1338,7 @@ public override int BinarySearch(object value) } } - public override int BinarySearch(object value, IComparer comparer) + public override int BinarySearch(object? value, IComparer? comparer) { lock (_root) { @@ -1347,7 +1347,7 @@ public override int BinarySearch(object value, IComparer comparer) } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int BinarySearch(int index, int count, object value, IComparer comparer) + public override int BinarySearch(int index, int count, object? value, IComparer? comparer) { lock (_root) { @@ -1371,7 +1371,7 @@ public override object Clone() } } - public override bool Contains(object item) + public override bool Contains(object? item) { lock (_root) { @@ -1421,7 +1421,7 @@ public override IEnumerator GetEnumerator(int index, int count) } } - public override int IndexOf(object value) + public override int IndexOf(object? value) { lock (_root) { @@ -1430,7 +1430,7 @@ public override int IndexOf(object value) } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int IndexOf(object value, int startIndex) + public override int IndexOf(object? value, int startIndex) { lock (_root) { @@ -1439,7 +1439,7 @@ public override int IndexOf(object value, int startIndex) } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int IndexOf(object value, int startIndex, int count) + public override int IndexOf(object? value, int startIndex, int count) { lock (_root) { @@ -1447,7 +1447,7 @@ public override int IndexOf(object value, int startIndex, int count) } } - public override void Insert(int index, object value) + public override void Insert(int index, object? value) { lock (_root) { @@ -1464,7 +1464,7 @@ public override void InsertRange(int index, ICollection c) } } - public override int LastIndexOf(object value) + public override int LastIndexOf(object? value) { lock (_root) { @@ -1473,7 +1473,7 @@ public override int LastIndexOf(object value) } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int LastIndexOf(object value, int startIndex) + public override int LastIndexOf(object? value, int startIndex) { lock (_root) { @@ -1482,7 +1482,7 @@ public override int LastIndexOf(object value, int startIndex) } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int LastIndexOf(object value, int startIndex, int count) + public override int LastIndexOf(object? value, int startIndex, int count) { lock (_root) { @@ -1490,7 +1490,7 @@ public override int LastIndexOf(object value, int startIndex, int count) } } - public override void Remove(object value) + public override void Remove(object? value) { lock (_root) { @@ -1550,7 +1550,7 @@ public override void Sort() } } - public override void Sort(IComparer comparer) + public override void Sort(IComparer? comparer) { lock (_root) { @@ -1559,7 +1559,7 @@ public override void Sort(IComparer comparer) } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override void Sort(int index, int count, IComparer comparer) + public override void Sort(int index, int count, IComparer? comparer) { lock (_root) { @@ -1567,7 +1567,7 @@ public override void Sort(int index, int count, IComparer comparer) } } - public override object[] ToArray() + public override object?[] ToArray() { lock (_root) { @@ -1626,7 +1626,7 @@ public virtual bool IsSynchronized get { return true; } } - public virtual object this[int index] + public virtual object? this[int index] { get { @@ -1649,7 +1649,7 @@ public virtual object SyncRoot get { return _root; } } - public virtual int Add(object value) + public virtual int Add(object? value) { lock (_root) { @@ -1666,7 +1666,7 @@ public virtual void Clear() } } - public virtual bool Contains(object item) + public virtual bool Contains(object? item) { lock (_root) { @@ -1690,7 +1690,7 @@ public virtual IEnumerator GetEnumerator() } } - public virtual int IndexOf(object value) + public virtual int IndexOf(object? value) { lock (_root) { @@ -1698,7 +1698,7 @@ public virtual int IndexOf(object value) } } - public virtual void Insert(int index, object value) + public virtual void Insert(int index, object? value) { lock (_root) { @@ -1706,7 +1706,7 @@ public virtual void Insert(int index, object value) } } - public virtual void Remove(object value) + public virtual void Remove(object? value) { lock (_root) { @@ -1752,7 +1752,7 @@ public virtual bool IsSynchronized get { return _list.IsSynchronized; } } - public virtual object this[int index] + public virtual object? this[int index] { get { @@ -1769,7 +1769,7 @@ public virtual object SyncRoot get { return _list.SyncRoot; } } - public virtual int Add(object obj) + public virtual int Add(object? obj) { throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } @@ -1779,7 +1779,7 @@ public virtual void Clear() throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } - public virtual bool Contains(object obj) + public virtual bool Contains(object? obj) { return _list.Contains(obj); } @@ -1794,17 +1794,17 @@ public virtual IEnumerator GetEnumerator() return _list.GetEnumerator(); } - public virtual int IndexOf(object value) + public virtual int IndexOf(object? value) { return _list.IndexOf(value); } - public virtual void Insert(int index, object obj) + public virtual void Insert(int index, object? obj) { throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } - public virtual void Remove(object value) + public virtual void Remove(object? value) { throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } @@ -1845,7 +1845,7 @@ public override bool IsSynchronized get { return _list.IsSynchronized; } } - public override object this[int index] + public override object? this[int index] { get { @@ -1863,7 +1863,7 @@ public override object SyncRoot get { return _list.SyncRoot; } } - public override int Add(object obj) + public override int Add(object? obj) { throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } @@ -1874,7 +1874,7 @@ public override void AddRange(ICollection c) } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int BinarySearch(int index, int count, object value, IComparer comparer) + public override int BinarySearch(int index, int count, object? value, IComparer? comparer) { return _list.BinarySearch(index, count, value, comparer); } @@ -1899,7 +1899,7 @@ public override object Clone() return arrayList; } - public override bool Contains(object obj) + public override bool Contains(object? obj) { return _list.Contains(obj); } @@ -1926,24 +1926,24 @@ public override IEnumerator GetEnumerator(int index, int count) return _list.GetEnumerator(index, count); } - public override int IndexOf(object value) + public override int IndexOf(object? value) { return _list.IndexOf(value); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int IndexOf(object value, int startIndex) + public override int IndexOf(object? value, int startIndex) { return _list.IndexOf(value, startIndex); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int IndexOf(object value, int startIndex, int count) + public override int IndexOf(object? value, int startIndex, int count) { return _list.IndexOf(value, startIndex, count); } - public override void Insert(int index, object obj) + public override void Insert(int index, object? obj) { throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } @@ -1954,24 +1954,24 @@ public override void InsertRange(int index, ICollection c) throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } - public override int LastIndexOf(object value) + public override int LastIndexOf(object? value) { return _list.LastIndexOf(value); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int LastIndexOf(object value, int startIndex) + public override int LastIndexOf(object? value, int startIndex) { return _list.LastIndexOf(value, startIndex); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int LastIndexOf(object value, int startIndex, int count) + public override int LastIndexOf(object? value, int startIndex, int count) { return _list.LastIndexOf(value, startIndex, count); } - public override void Remove(object value) + public override void Remove(object? value) { throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } @@ -2012,13 +2012,13 @@ public override void Reverse(int index, int count) } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override void Sort(int index, int count, IComparer comparer) + public override void Sort(int index, int count, IComparer? comparer) { _list.Sort(index, count, comparer); _version = _list._version; } - public override object[] ToArray() + public override object?[] ToArray() { return _list.ToArray(); } @@ -2064,7 +2064,7 @@ public virtual bool IsSynchronized get { return _list.IsSynchronized; } } - public virtual object this[int index] + public virtual object? this[int index] { get { @@ -2081,7 +2081,7 @@ public virtual object SyncRoot get { return _list.SyncRoot; } } - public virtual int Add(object obj) + public virtual int Add(object? obj) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } @@ -2091,7 +2091,7 @@ public virtual void Clear() throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } - public virtual bool Contains(object obj) + public virtual bool Contains(object? obj) { return _list.Contains(obj); } @@ -2106,17 +2106,17 @@ public virtual IEnumerator GetEnumerator() return _list.GetEnumerator(); } - public virtual int IndexOf(object value) + public virtual int IndexOf(object? value) { return _list.IndexOf(value); } - public virtual void Insert(int index, object obj) + public virtual void Insert(int index, object? obj) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } - public virtual void Remove(object value) + public virtual void Remove(object? value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } @@ -2156,7 +2156,7 @@ public override bool IsSynchronized get { return _list.IsSynchronized; } } - public override object this[int index] + public override object? this[int index] { get { @@ -2173,7 +2173,7 @@ public override object SyncRoot get { return _list.SyncRoot; } } - public override int Add(object obj) + public override int Add(object? obj) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } @@ -2184,7 +2184,7 @@ public override void AddRange(ICollection c) } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int BinarySearch(int index, int count, object value, IComparer comparer) + public override int BinarySearch(int index, int count, object? value, IComparer? comparer) { return _list.BinarySearch(index, count, value, comparer); } @@ -2210,7 +2210,7 @@ public override object Clone() return arrayList; } - public override bool Contains(object obj) + public override bool Contains(object? obj) { return _list.Contains(obj); } @@ -2237,24 +2237,24 @@ public override IEnumerator GetEnumerator(int index, int count) return _list.GetEnumerator(index, count); } - public override int IndexOf(object value) + public override int IndexOf(object? value) { return _list.IndexOf(value); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int IndexOf(object value, int startIndex) + public override int IndexOf(object? value, int startIndex) { return _list.IndexOf(value, startIndex); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int IndexOf(object value, int startIndex, int count) + public override int IndexOf(object? value, int startIndex, int count) { return _list.IndexOf(value, startIndex, count); } - public override void Insert(int index, object obj) + public override void Insert(int index, object? obj) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } @@ -2265,24 +2265,24 @@ public override void InsertRange(int index, ICollection c) throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } - public override int LastIndexOf(object value) + public override int LastIndexOf(object? value) { return _list.LastIndexOf(value); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int LastIndexOf(object value, int startIndex) + public override int LastIndexOf(object? value, int startIndex) { return _list.LastIndexOf(value, startIndex); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int LastIndexOf(object value, int startIndex, int count) + public override int LastIndexOf(object? value, int startIndex, int count) { return _list.LastIndexOf(value, startIndex, count); } - public override void Remove(object value) + public override void Remove(object? value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } @@ -2321,12 +2321,12 @@ public override void Reverse(int index, int count) } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override void Sort(int index, int count, IComparer comparer) + public override void Sort(int index, int count, IComparer? comparer) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } - public override object[] ToArray() + public override object?[] ToArray() { return _list.ToArray(); } @@ -2353,7 +2353,7 @@ private sealed class ArrayListEnumerator : IEnumerator, ICloneable private int _index; private int _endIndex; // Where to stop. private int _version; - private object _currentElement; + private object? _currentElement; private int _startIndex; // Save this for Reset. internal ArrayListEnumerator(ArrayList list, int index, int count) @@ -2384,7 +2384,7 @@ public bool MoveNext() return false; } - public object Current + public object? Current { get { @@ -2436,7 +2436,7 @@ private void InternalUpdateVersion() _version++; } - public override int Add(object value) + public override int Add(object? value) { InternalUpdateRange(); _baseList.Insert(_baseIndex + _baseSize, value); @@ -2461,7 +2461,7 @@ public override void AddRange(ICollection c) } } - public override int BinarySearch(int index, int count, object value, IComparer comparer) + public override int BinarySearch(int index, int count, object? value, IComparer? comparer) { if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -2508,7 +2508,7 @@ public override object Clone() return arrayList; } - public override bool Contains(object item) + public override bool Contains(object? item) { InternalUpdateRange(); if (item == null) @@ -2521,7 +2521,7 @@ public override bool Contains(object item) else { for (int i = 0; i < _baseSize; i++) - if (_baseList[_baseIndex + i] != null && _baseList[_baseIndex + i].Equals(item)) + if (_baseList[_baseIndex + i] != null && _baseList[_baseIndex + i]!.Equals(item)) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) return true; return false; } @@ -2619,7 +2619,7 @@ public override object SyncRoot } - public override int IndexOf(object value) + public override int IndexOf(object? value) { InternalUpdateRange(); int i = _baseList.IndexOf(value, _baseIndex, _baseSize); @@ -2627,7 +2627,7 @@ public override int IndexOf(object value) return -1; } - public override int IndexOf(object value, int startIndex) + public override int IndexOf(object? value, int startIndex) { if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -2640,7 +2640,7 @@ public override int IndexOf(object value, int startIndex) return -1; } - public override int IndexOf(object value, int startIndex, int count) + public override int IndexOf(object? value, int startIndex, int count) { if (startIndex < 0 || startIndex > _baseSize) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); @@ -2654,7 +2654,7 @@ public override int IndexOf(object value, int startIndex, int count) return -1; } - public override void Insert(int index, object value) + public override void Insert(int index, object? value) { if (index < 0 || index > _baseSize) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); @@ -2682,7 +2682,7 @@ public override void InsertRange(int index, ICollection c) } } - public override int LastIndexOf(object value) + public override int LastIndexOf(object? value) { InternalUpdateRange(); int i = _baseList.LastIndexOf(value, _baseIndex + _baseSize - 1, _baseSize); @@ -2691,13 +2691,13 @@ public override int LastIndexOf(object value) } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int LastIndexOf(object value, int startIndex) + public override int LastIndexOf(object? value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. - public override int LastIndexOf(object value, int startIndex, int count) + public override int LastIndexOf(object? value, int startIndex, int count) { InternalUpdateRange(); if (_baseSize == 0) @@ -2767,7 +2767,7 @@ public override void SetRange(int index, ICollection c) } } - public override void Sort(int index, int count, IComparer comparer) + public override void Sort(int index, int count, IComparer? comparer) { if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -2779,7 +2779,7 @@ public override void Sort(int index, int count, IComparer comparer) InternalUpdateVersion(); } - public override object this[int index] + public override object? this[int index] { get { @@ -2796,11 +2796,11 @@ public override object this[int index] } } - public override object[] ToArray() + public override object?[] ToArray() { InternalUpdateRange(); if (_baseSize == 0) - return Array.Empty(); + return Array.Empty(); object[] array = new object[_baseSize]; Array.Copy(_baseList._items, _baseIndex, array, 0, _baseSize); return array; @@ -2828,7 +2828,7 @@ private sealed class ArrayListEnumeratorSimple : IEnumerator, ICloneable private ArrayList _list; private int _index; private int _version; - private object _currentElement; + private object? _currentElement; private bool _isArrayList; // this object is used to indicate enumeration has not started or has terminated private static object s_dummyObject = new object(); @@ -2881,11 +2881,11 @@ public bool MoveNext() } } - public object Current + public object? Current { get { - object temp = _currentElement; + object? temp = _currentElement; if (s_dummyObject == temp) { // check if enumeration has not started or has terminated if (_index == -1) @@ -2927,7 +2927,7 @@ public ArrayListDebugView(ArrayList arrayList) } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public object[] Items + public object?[] Items { get { diff --git a/src/Common/src/CoreLib/System/Collections/Comparer.cs b/src/Common/src/CoreLib/System/Collections/Comparer.cs index 24a6cbff622a..f74bd8577617 100644 --- a/src/Common/src/CoreLib/System/Collections/Comparer.cs +++ b/src/Common/src/CoreLib/System/Collections/Comparer.cs @@ -35,7 +35,7 @@ private Comparer(SerializationInfo info, StreamingContext context) if (info == null) throw new ArgumentNullException(nameof(info)); - _compareInfo = (CompareInfo)info.GetValue("CompareInfo", typeof(CompareInfo)); + _compareInfo = (CompareInfo)info.GetValue("CompareInfo", typeof(CompareInfo))!; } public void GetObjectData(SerializationInfo info, StreamingContext context) @@ -52,13 +52,13 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) // If a doesn't implement IComparable and b does, -(b.CompareTo(a)) is returned. // Otherwise an exception is thrown. // - public int Compare(object a, object b) + public int Compare(object? a, object? b) { if (a == b) return 0; if (a == null) return -1; if (b == null) return 1; - string sa = a as string; + string? sa = a as string; if (sa != null && b is string sb) return _compareInfo.Compare(sa, sb); diff --git a/src/Common/src/CoreLib/System/Collections/CompatibleComparer.cs b/src/Common/src/CoreLib/System/Collections/CompatibleComparer.cs index 5342dcd6fb91..f4042e50029d 100644 --- a/src/Common/src/CoreLib/System/Collections/CompatibleComparer.cs +++ b/src/Common/src/CoreLib/System/Collections/CompatibleComparer.cs @@ -2,28 +2,29 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #pragma warning disable 618 // obsolete types namespace System.Collections { internal sealed class CompatibleComparer : IEqualityComparer { - private readonly IHashCodeProvider _hcp; - private readonly IComparer _comparer; + private readonly IHashCodeProvider? _hcp; + private readonly IComparer? _comparer; - internal CompatibleComparer(IHashCodeProvider hashCodeProvider, IComparer comparer) + internal CompatibleComparer(IHashCodeProvider? hashCodeProvider, IComparer? comparer) { _hcp = hashCodeProvider; _comparer = comparer; } - internal IHashCodeProvider HashCodeProvider => _hcp; + internal IHashCodeProvider? HashCodeProvider => _hcp; - internal IComparer Comparer => _comparer; + internal IComparer? Comparer => _comparer; - public new bool Equals(object a, object b) => Compare(a, b) == 0; + public new bool Equals(object? a, object? b) => Compare(a, b) == 0; - public int Compare(object a, object b) + public int Compare(object? a, object? b) { if (a == b) return 0; diff --git a/src/Common/src/CoreLib/System/Collections/Concurrent/ConcurrentQueue.cs b/src/Common/src/CoreLib/System/Collections/Concurrent/ConcurrentQueue.cs index 593e3a724aa2..e62e37272a2e 100644 --- a/src/Common/src/CoreLib/System/Collections/Concurrent/ConcurrentQueue.cs +++ b/src/Common/src/CoreLib/System/Collections/Concurrent/ConcurrentQueue.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Threading; namespace System.Collections.Concurrent @@ -100,7 +100,7 @@ public ConcurrentQueue(IEnumerable collection) // Initialize the segment and add all of the data to it. _tail = _head = new ConcurrentQueueSegment(length); - foreach (T item in collection!) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + foreach (T item in collection!) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { Enqueue(item); } @@ -147,7 +147,7 @@ void ICollection.CopyTo(Array array, int index) // Otherwise, fall back to the slower path that first copies the contents // to an array, and then uses that array's non-generic CopyTo to do the copy. - ToArray().CopyTo(array!, index); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + ToArray().CopyTo(array!, index); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } /// @@ -164,7 +164,7 @@ void ICollection.CopyTo(Array array, int index) /// cref="ICollection"/>. This property is not supported. /// /// The SyncRoot property is not supported. - object ICollection.SyncRoot { get { ThrowHelper.ThrowNotSupportedException(ExceptionResource.ConcurrentCollection_SyncRoot_NotSupported); return default!; } } // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + object ICollection.SyncRoot { get { ThrowHelper.ThrowNotSupportedException(ExceptionResource.ConcurrentCollection_SyncRoot_NotSupported); return default!; } } // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected /// Returns an enumerator that iterates through a collection. /// An that can be used to iterate through the collection. @@ -462,7 +462,7 @@ public void CopyTo(T[] array, int index) // Get the number of items to be enumerated long count = GetCount(head, headHead, tail, tailTail); - if (index > array!.Length - count) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + if (index > array!.Length - count) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } @@ -679,12 +679,12 @@ private void EnqueueSlow(T item) /// true if an element was removed and returned from the beginning of the /// successfully; otherwise, false. /// - public bool TryDequeue(out T result) => // TODO-GENERIC-NULLABLE + public bool TryDequeue([MaybeNullWhen(false)] out T result) => _head.TryDequeue(out result) || // fast-path that operates just on the head segment TryDequeueSlow(out result); // slow path that needs to fix up segments /// Tries to dequeue an item, removing empty segments as needed. - private bool TryDequeueSlow(out T item) + private bool TryDequeueSlow([MaybeNullWhen(false)] out T item) { while (true) { @@ -702,7 +702,7 @@ private bool TryDequeueSlow(out T item) // check and this check, another item could have arrived). if (head._nextSegment == null) { - item = default!; // TODO-NULLABLE-GENERIC + item = default!; return false; } @@ -743,13 +743,13 @@ private bool TryDequeueSlow(out T item) /// For determining whether the collection contains any items, use of the /// property is recommended rather than peeking. /// - public bool TryPeek(out T result) => TryPeek(out result, resultUsed: true); // TODO-GENERIC-NULLABLE + public bool TryPeek([MaybeNullWhen(false)] out T result) => TryPeek(out result, resultUsed: true); /// Attempts to retrieve the value for the first element in the queue. /// The value of the first element, if found. /// true if the result is needed; otherwise false if only the true/false outcome is needed. /// true if an element was found; otherwise, false. - private bool TryPeek(out T result, bool resultUsed) + private bool TryPeek([MaybeNullWhen(false)] out T result, bool resultUsed) { // Starting with the head segment, look through all of the segments // for the first one we can find that's not empty. @@ -796,7 +796,7 @@ private bool TryPeek(out T result, bool resultUsed) // and we'll traverse to that segment. } - result = default!; // TODO-NULLABLE-GENERIC + result = default!; return false; } diff --git a/src/Common/src/CoreLib/System/Collections/Concurrent/ConcurrentQueueSegment.cs b/src/Common/src/CoreLib/System/Collections/Concurrent/ConcurrentQueueSegment.cs index c120d777621e..fcf0539df4ce 100644 --- a/src/Common/src/CoreLib/System/Collections/Concurrent/ConcurrentQueueSegment.cs +++ b/src/Common/src/CoreLib/System/Collections/Concurrent/ConcurrentQueueSegment.cs @@ -4,6 +4,7 @@ #nullable enable using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Threading; @@ -127,7 +128,7 @@ internal static int RoundUpToPowerOf2(int i) } /// Tries to dequeue an element from the queue. - public bool TryDequeue(out T item) // TODO-NULLABLE-GENERIC + public bool TryDequeue([MaybeNullWhen(false)] out T item) { Slot[] slots = _slots; @@ -165,7 +166,7 @@ public bool TryDequeue(out T item) // TODO-NULLABLE-GENERIC // If we're preserving, though, we don't zero out the slot, as we need it for // enumerations, peeking, ToArray, etc. And we don't update the sequence number, // so that an enqueuer will see it as full and be forced to move to a new segment. - slots[slotsIndex].Item = default!; // TODO-NULLABLE-GENERIC + slots[slotsIndex].Item = default!; // TODO-NULLABLE: Remove ! when nullable attributes are respected Volatile.Write(ref slots[slotsIndex].SequenceNumber, currentHead + slots.Length); } return true; @@ -184,7 +185,7 @@ public bool TryDequeue(out T item) // TODO-NULLABLE-GENERIC int currentTail = Volatile.Read(ref _headAndTail.Tail); if (currentTail - currentHead <= 0 || (frozen && (currentTail - FreezeOffset - currentHead <= 0))) { - item = default!; // TODO-NULLABLE-GENERIC + item = default!; return false; } @@ -199,7 +200,7 @@ public bool TryDequeue(out T item) // TODO-NULLABLE-GENERIC } /// Tries to peek at an element from the queue, without removing it. - public bool TryPeek(out T result, bool resultUsed) // TODO-NULLABLE-GENERIC + public bool TryPeek([MaybeNullWhen(false)] out T result, bool resultUsed) { if (resultUsed) { @@ -229,7 +230,7 @@ public bool TryPeek(out T result, bool resultUsed) // TODO-NULLABLE-GENERIC int diff = sequenceNumber - (currentHead + 1); if (diff == 0) { - result = resultUsed ? slots[slotsIndex].Item : default!; // TODO-NULLABLE-GENERIC + result = resultUsed ? slots[slotsIndex].Item : default!; return true; } else if (diff < 0) @@ -245,7 +246,7 @@ public bool TryPeek(out T result, bool resultUsed) // TODO-NULLABLE-GENERIC int currentTail = Volatile.Read(ref _headAndTail.Tail); if (currentTail - currentHead <= 0 || (frozen && (currentTail - FreezeOffset - currentHead <= 0))) { - result = default!; // TODO-NULLABLE-GENERIC + result = default!; return false; } @@ -322,7 +323,7 @@ public bool TryEnqueue(T item) internal struct Slot { /// The item. - public T Item; // SOS's ThreadPool command depends on this being at the beginning of the struct when T is a reference type + [AllowNull, MaybeNull] public T Item; // SOS's ThreadPool command depends on this being at the beginning of the struct when T is a reference type /// The sequence number for this slot, used to synchronize between enqueuers and dequeuers. public int SequenceNumber; } diff --git a/src/Common/src/CoreLib/System/Collections/Concurrent/IProducerConsumerCollection.cs b/src/Common/src/CoreLib/System/Collections/Concurrent/IProducerConsumerCollection.cs index 797bb0863dba..e33c840b4600 100644 --- a/src/Common/src/CoreLib/System/Collections/Concurrent/IProducerConsumerCollection.cs +++ b/src/Common/src/CoreLib/System/Collections/Concurrent/IProducerConsumerCollection.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace System.Collections.Concurrent { @@ -59,7 +59,7 @@ public interface IProducerConsumerCollection : IEnumerable, ICollection /// unspecified. /// /// true if an object was removed and returned successfully; otherwise, false. - bool TryTake(out T item); // TODO-NULLABLE-GENERIC + bool TryTake([MaybeNullWhen(false)] out T item); /// /// Copies the elements contained in the to a new array. diff --git a/src/Common/src/CoreLib/System/Collections/Concurrent/IProducerConsumerCollectionDebugView.cs b/src/Common/src/CoreLib/System/Collections/Concurrent/IProducerConsumerCollectionDebugView.cs index f30f8f66fcc6..e848b2fddd57 100644 --- a/src/Common/src/CoreLib/System/Collections/Concurrent/IProducerConsumerCollectionDebugView.cs +++ b/src/Common/src/CoreLib/System/Collections/Concurrent/IProducerConsumerCollectionDebugView.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Collections.Concurrent diff --git a/src/Common/src/CoreLib/System/Collections/DictionaryEntry.cs b/src/Common/src/CoreLib/System/Collections/DictionaryEntry.cs index 187301a08f49..7e86f388d0de 100644 --- a/src/Common/src/CoreLib/System/Collections/DictionaryEntry.cs +++ b/src/Common/src/CoreLib/System/Collections/DictionaryEntry.cs @@ -13,11 +13,11 @@ namespace System.Collections public struct DictionaryEntry { private object _key; // Do not rename (binary serialization) - private object _value; // Do not rename (binary serialization) + private object? _value; // Do not rename (binary serialization) // Constructs a new DictionaryEnumerator by setting the Key // and Value fields appropriately. - public DictionaryEntry(object key, object value) + public DictionaryEntry(object key, object? value) { _key = key; _value = value; @@ -36,7 +36,7 @@ public object Key } } - public object Value + public object? Value { get { @@ -50,7 +50,7 @@ public object Value } [EditorBrowsable(EditorBrowsableState.Never)] - public void Deconstruct(out object key, out object value) + public void Deconstruct(out object key, out object? value) { key = Key; value = Value; diff --git a/src/Common/src/CoreLib/System/Collections/Generic/ArraySortHelper.cs b/src/Common/src/CoreLib/System/Collections/Generic/ArraySortHelper.cs index 03b9865044f6..2ec14db77823 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/ArraySortHelper.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/ArraySortHelper.cs @@ -14,7 +14,7 @@ ===========================================================*/ using System.Diagnostics; -using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; namespace System.Collections.Generic { @@ -38,7 +38,8 @@ internal static int FloorLog2PlusOne(int n) return result; } - internal static void ThrowOrIgnoreBadComparer(object comparer) + [DoesNotReturn] + internal static void ThrowOrIgnoreBadComparer(object? comparer) { throw new ArgumentException(SR.Format(SR.Arg_BogusIComparer, comparer)); } @@ -48,7 +49,7 @@ internal partial class ArraySortHelper { #region IArraySortHelper Members - public void Sort(T[] keys, int index, int length, IComparer comparer) + public void Sort(T[] keys, int index, int length, IComparer? comparer) { Debug.Assert(keys != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); @@ -74,7 +75,7 @@ public void Sort(T[] keys, int index, int length, IComparer comparer) } } - public int BinarySearch(T[] array, int index, int length, T value, IComparer comparer) + public int BinarySearch(T[] array, int index, int length, T value, IComparer? comparer) { try { @@ -335,7 +336,7 @@ internal partial class GenericArraySortHelper #region IArraySortHelper Members - public void Sort(T[] keys, int index, int length, IComparer comparer) + public void Sort(T[] keys, int index, int length, IComparer? comparer) { Debug.Assert(keys != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); @@ -361,7 +362,7 @@ public void Sort(T[] keys, int index, int length, IComparer comparer) } } - public int BinarySearch(T[] array, int index, int length, T value, IComparer comparer) + public int BinarySearch(T[] array, int index, int length, T value, IComparer? comparer) { Debug.Assert(array != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!"); @@ -624,7 +625,7 @@ private static void InsertionSort(T[] keys, int lo, int hi) internal partial class ArraySortHelper { - public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer comparer) + public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer? comparer) { Debug.Assert(keys != null, "Check the arguments in the caller!"); // Precondition on interface method Debug.Assert(values != null, "Check the arguments in the caller!"); @@ -871,7 +872,7 @@ private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi, internal partial class GenericArraySortHelper where TKey : IComparable { - public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer comparer) + public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer? comparer) { Debug.Assert(keys != null, "Check the arguments in the caller!"); Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!"); diff --git a/src/Common/src/CoreLib/System/Collections/Generic/Comparer.cs b/src/Common/src/CoreLib/System/Collections/Generic/Comparer.cs index f7c6cf81dd65..80187beedf88 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/Comparer.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/Comparer.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.Serialization; @@ -21,9 +22,9 @@ public static Comparer Create(Comparison comparison) return new ComparisonComparer(comparison); } - public abstract int Compare(T x, T y); + public abstract int Compare([AllowNull] T x, [AllowNull] T y); - int IComparer.Compare(object x, object y) + int IComparer.Compare(object? x, object? y) { if (x == null) return y == null ? 0 : -1; if (y == null) return 1; @@ -58,7 +59,7 @@ public override int Compare(T x, T y) // Needs to be public to support binary serialization compatibility public sealed partial class GenericComparer : Comparer where T : IComparable { - public override int Compare(T x, T y) + public override int Compare([AllowNull] T x, [AllowNull] T y) { if (x != null) { @@ -70,7 +71,7 @@ public override int Compare(T x, T y) } // Equals method for the comparer itself. - public override bool Equals(object obj) => + public override bool Equals(object? obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => @@ -94,7 +95,7 @@ public override int Compare(T? x, T? y) } // Equals method for the comparer itself. - public override bool Equals(object obj) => + public override bool Equals(object? obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => @@ -106,13 +107,13 @@ public override int GetHashCode() => // Needs to be public to support binary serialization compatibility public sealed partial class ObjectComparer : Comparer { - public override int Compare(T x, T y) + public override int Compare([AllowNull] T x, [AllowNull] T y) { return System.Collections.Comparer.Default.Compare(x, y); } // Equals method for the comparer itself. - public override bool Equals(object obj) => + public override bool Equals(object? obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => @@ -130,7 +131,7 @@ private EnumComparer(SerializationInfo info, StreamingContext context) { } // public override int Compare(T x, T y) is runtime-specific // Equals method for the comparer itself. - public override bool Equals(object obj) => + public override bool Equals(object? obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => diff --git a/src/Common/src/CoreLib/System/Collections/Generic/Dictionary.cs b/src/Common/src/CoreLib/System/Collections/Generic/Dictionary.cs index 0a36cb5f7681..d79924cfdc9d 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/Dictionary.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/Dictionary.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.Serialization; @@ -33,7 +34,7 @@ internal enum InsertionBehavior : byte [DebuggerDisplay("Count = {Count}")] [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public class Dictionary : IDictionary, IDictionary, IReadOnlyDictionary, ISerializable, IDeserializationCallback + public class Dictionary : IDictionary, IDictionary, IReadOnlyDictionary, ISerializable, IDeserializationCallback where TKey : object { private struct Entry { @@ -46,15 +47,15 @@ private struct Entry public TValue value; // Value of entry } - private int[] _buckets; - private Entry[] _entries; + private int[]? _buckets; + private Entry[]? _entries; private int _count; private int _freeList; private int _freeCount; private int _version; - private IEqualityComparer _comparer; - private KeyCollection _keys; - private ValueCollection _values; + private IEqualityComparer? _comparer; + private KeyCollection? _keys; + private ValueCollection? _values; private const int StartOfFreeList = -3; // constants for serialization @@ -67,9 +68,9 @@ public Dictionary() : this(0, null) { } public Dictionary(int capacity) : this(capacity, null) { } - public Dictionary(IEqualityComparer comparer) : this(0, comparer) { } + public Dictionary(IEqualityComparer? comparer) : this(0, comparer) { } - public Dictionary(int capacity, IEqualityComparer comparer) + public Dictionary(int capacity, IEqualityComparer? comparer) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); if (capacity > 0) Initialize(capacity); @@ -87,7 +88,7 @@ public Dictionary(int capacity, IEqualityComparer comparer) public Dictionary(IDictionary dictionary) : this(dictionary, null) { } - public Dictionary(IDictionary dictionary, IEqualityComparer comparer) : + public Dictionary(IDictionary dictionary, IEqualityComparer? comparer) : this(dictionary != null ? dictionary.Count : 0, comparer) { if (dictionary == null) @@ -99,14 +100,14 @@ public Dictionary(IDictionary dictionary, IEqualityComparer // avoid the enumerator allocation and overhead by looping through the entries array directly. // We only do this when dictionary is Dictionary and not a subclass, to maintain // back-compat with subclasses that may have overridden the enumerator behavior. - if (dictionary.GetType() == typeof(Dictionary)) + if (dictionary!.GetType() == typeof(Dictionary)) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { Dictionary d = (Dictionary)dictionary; int count = d._count; - Entry[] entries = d._entries; + Entry[]? entries = d._entries; for (int i = 0; i < count; i++) { - if (entries[i].next >= -1) + if (entries![i].next >= -1) { Add(entries[i].key, entries[i].value); } @@ -122,7 +123,7 @@ public Dictionary(IDictionary dictionary, IEqualityComparer public Dictionary(IEnumerable> collection) : this(collection, null) { } - public Dictionary(IEnumerable> collection, IEqualityComparer comparer) : + public Dictionary(IEnumerable> collection, IEqualityComparer? comparer) : this((collection as ICollection>)?.Count ?? 0, comparer) { if (collection == null) @@ -130,7 +131,7 @@ public Dictionary(IEnumerable> collection, IEqualityC ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } - foreach (KeyValuePair pair in collection) + foreach (KeyValuePair pair in collection!) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { Add(pair.Key, pair.Value); } @@ -216,9 +217,9 @@ public TValue this[TKey key] get { int i = FindEntry(key); - if (i >= 0) return _entries[i].value; + if (i >= 0) return _entries![i].value; ThrowHelper.ThrowKeyNotFoundException(key); - return default; + return default!; // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } set { @@ -239,7 +240,7 @@ void ICollection>.Add(KeyValuePair keyV bool ICollection>.Contains(KeyValuePair keyValuePair) { int i = FindEntry(keyValuePair.Key); - if (i >= 0 && EqualityComparer.Default.Equals(_entries[i].value, keyValuePair.Value)) + if (i >= 0 && EqualityComparer.Default.Equals(_entries![i].value, keyValuePair.Value)) { return true; } @@ -249,7 +250,7 @@ bool ICollection>.Contains(KeyValuePair bool ICollection>.Remove(KeyValuePair keyValuePair) { int i = FindEntry(keyValuePair.Key); - if (i >= 0 && EqualityComparer.Default.Equals(_entries[i].value, keyValuePair.Value)) + if (i >= 0 && EqualityComparer.Default.Equals(_entries![i].value, keyValuePair.Value)) { Remove(keyValuePair.Key); return true; @@ -262,6 +263,9 @@ public void Clear() int count = _count; if (count > 0) { + Debug.Assert(_buckets != null, "_buckets should be non-null"); + Debug.Assert(_entries != null, "_entries should be non-null"); + Array.Clear(_buckets, 0, _buckets.Length); _count = 0; @@ -276,22 +280,22 @@ public bool ContainsKey(TKey key) public bool ContainsValue(TValue value) { - Entry[] entries = _entries; + Entry[]? entries = _entries; if (value == null) { for (int i = 0; i < _count; i++) { - if (entries[i].next >= -1 && entries[i].value == null) return true; + if (entries![i].next >= -1 && entries[i].value == null) return true; } } else { - if (default(TValue) != null) + if (default(TValue)! != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { // ValueType: Devirtualize with EqualityComparer.Default intrinsic for (int i = 0; i < _count; i++) { - if (entries[i].next >= -1 && EqualityComparer.Default.Equals(entries[i].value, value)) return true; + if (entries![i].next >= -1 && EqualityComparer.Default.Equals(entries[i].value, value)) return true; } } else @@ -302,7 +306,7 @@ public bool ContainsValue(TValue value) EqualityComparer defaultComparer = EqualityComparer.Default; for (int i = 0; i < _count; i++) { - if (entries[i].next >= -1 && defaultComparer.Equals(entries[i].value, value)) return true; + if (entries![i].next >= -1 && defaultComparer.Equals(entries[i].value, value)) return true; } } } @@ -316,7 +320,7 @@ private void CopyTo(KeyValuePair[] array, int index) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if ((uint)index > (uint)array.Length) + if ((uint)index > (uint)array!.Length) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } @@ -327,10 +331,10 @@ private void CopyTo(KeyValuePair[] array, int index) } int count = _count; - Entry[] entries = _entries; + Entry[]? entries = _entries; for (int i = 0; i < count; i++) { - if (entries[i].next >= -1) + if (entries![i].next >= -1) { array[index++] = new KeyValuePair(entries[i].key, entries[i].value); } @@ -350,7 +354,7 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info); } - info.AddValue(VersionName, _version); + info!.AddValue(VersionName, _version); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected info.AddValue(ComparerName, _comparer ?? EqualityComparer.Default, typeof(IEqualityComparer)); info.AddValue(HashSizeName, _buckets == null ? 0 : _buckets.Length); // This is the length of the bucket array @@ -370,18 +374,19 @@ private int FindEntry(TKey key) } int i = -1; - int[] buckets = _buckets; - Entry[] entries = _entries; + int[]? buckets = _buckets; + Entry[]? entries = _entries; int collisionCount = 0; if (buckets != null) { - IEqualityComparer comparer = _comparer; + Debug.Assert(entries != null, "expected entries to be != null"); + IEqualityComparer? comparer = _comparer; if (comparer == null) { - uint hashCode = (uint)key.GetHashCode(); + uint hashCode = (uint)key!.GetHashCode(); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected // Value in _buckets is 1-based i = buckets[hashCode % (uint)buckets.Length] - 1; - if (default(TKey) != null) + if (default(TKey)! != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { // ValueType: Devirtualize with EqualityComparer.Default intrinsic do @@ -481,11 +486,13 @@ private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior) { Initialize(0); } + Debug.Assert(_buckets != null); - Entry[] entries = _entries; - IEqualityComparer comparer = _comparer; + Entry[]? entries = _entries; + Debug.Assert(entries != null, "expected entries to be non-null"); - uint hashCode = (uint)((comparer == null) ? key.GetHashCode() : comparer.GetHashCode(key)); + IEqualityComparer? comparer = _comparer; + uint hashCode = (uint)((comparer == null) ? key!.GetHashCode() : comparer.GetHashCode(key)); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected int collisionCount = 0; ref int bucket = ref _buckets[hashCode % (uint)_buckets.Length]; @@ -494,7 +501,7 @@ private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior) if (comparer == null) { - if (default(TKey) != null) + if (default(TKey)! != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { // ValueType: Devirtualize with EqualityComparer.Default intrinsic do @@ -637,7 +644,7 @@ private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior) entries = _entries; } - ref Entry entry = ref entries[index]; + ref Entry entry = ref entries![index]; if (updateFreeList) { @@ -655,7 +662,7 @@ private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior) _version++; // Value types never rehash - if (default(TKey) == null && collisionCount > HashHelpers.HashCollisionThreshold && comparer is NonRandomizedStringEqualityComparer) + if (default(TKey)! == null && collisionCount > HashHelpers.HashCollisionThreshold && comparer is NonRandomizedStringEqualityComparer) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { // If we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing // i.e. EqualityComparer.Default. @@ -679,13 +686,13 @@ public virtual void OnDeserialization(object sender) int realVersion = siInfo.GetInt32(VersionName); int hashsize = siInfo.GetInt32(HashSizeName); - _comparer = (IEqualityComparer)siInfo.GetValue(ComparerName, typeof(IEqualityComparer)); + _comparer = (IEqualityComparer)siInfo.GetValue(ComparerName, typeof(IEqualityComparer))!; // When serialized if comparer is null, we use the default. if (hashsize != 0) { Initialize(hashsize); - KeyValuePair[] array = (KeyValuePair[]) + KeyValuePair[]? array = (KeyValuePair[]?) siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair[])); if (array == null) @@ -693,7 +700,7 @@ public virtual void OnDeserialization(object sender) ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys); } - for (int i = 0; i < array.Length; i++) + for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { if (array[i].Key == null) { @@ -717,7 +724,8 @@ private void Resize() private void Resize(int newSize, bool forceNewHashCodes) { // Value types never rehash - Debug.Assert(!forceNewHashCodes || default(TKey) == null); + Debug.Assert(!forceNewHashCodes || default(TKey)! == null); // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) + Debug.Assert(_entries != null, "_entries should be non-null"); Debug.Assert(newSize >= _entries.Length); int[] buckets = new int[newSize]; @@ -726,7 +734,7 @@ private void Resize(int newSize, bool forceNewHashCodes) int count = _count; Array.Copy(_entries, 0, entries, 0, count); - if (default(TKey) == null && forceNewHashCodes) + if (default(TKey)! == null && forceNewHashCodes) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { for (int i = 0; i < count; i++) { @@ -764,12 +772,13 @@ public bool Remove(TKey key) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } - int[] buckets = _buckets; - Entry[] entries = _entries; + int[]? buckets = _buckets; + Entry[]? entries = _entries; int collisionCount = 0; if (buckets != null) { - uint hashCode = (uint)(_comparer?.GetHashCode(key) ?? key.GetHashCode()); + Debug.Assert(entries != null, "entries should be non-null"); + uint hashCode = (uint)(_comparer?.GetHashCode(key) ?? key!.GetHashCode()); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected uint bucket = hashCode % (uint)buckets.Length; int last = -1; // Value in buckets is 1-based @@ -796,11 +805,11 @@ public bool Remove(TKey key) if (RuntimeHelpers.IsReferenceOrContainsReferences()) { - entry.key = default; + entry.key = default!; } if (RuntimeHelpers.IsReferenceOrContainsReferences()) { - entry.value = default; + entry.value = default!; } _freeList = i; _freeCount++; @@ -824,19 +833,20 @@ public bool Remove(TKey key) // This overload is a copy of the overload Remove(TKey key) with one additional // statement to copy the value for entry being removed into the output parameter. // Code has been intentionally duplicated for performance reasons. - public bool Remove(TKey key, out TValue value) + public bool Remove(TKey key, [MaybeNullWhen(false)] out TValue value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } - int[] buckets = _buckets; - Entry[] entries = _entries; + int[]? buckets = _buckets; + Entry[]? entries = _entries; int collisionCount = 0; if (buckets != null) { - uint hashCode = (uint)(_comparer?.GetHashCode(key) ?? key.GetHashCode()); + Debug.Assert(entries != null, "entries should be non-null"); + uint hashCode = (uint)(_comparer?.GetHashCode(key) ?? key!.GetHashCode()); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected uint bucket = hashCode % (uint)buckets.Length; int last = -1; // Value in buckets is 1-based @@ -865,11 +875,11 @@ public bool Remove(TKey key, out TValue value) if (RuntimeHelpers.IsReferenceOrContainsReferences()) { - entry.key = default; + entry.key = default!; } if (RuntimeHelpers.IsReferenceOrContainsReferences()) { - entry.value = default; + entry.value = default!; } _freeList = i; _freeCount++; @@ -887,19 +897,19 @@ public bool Remove(TKey key, out TValue value) collisionCount++; } } - value = default; + value = default!; return false; } - public bool TryGetValue(TKey key, out TValue value) + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { int i = FindEntry(key); if (i >= 0) { - value = _entries[i].value; + value = _entries![i].value; return true; } - value = default; + value = default!; return false; } @@ -915,7 +925,7 @@ void ICollection.CopyTo(Array array, int index) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - if (array.Rank != 1) + if (array!.Rank != 1) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); if (array.GetLowerBound(0) != 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); @@ -930,10 +940,10 @@ void ICollection.CopyTo(Array array, int index) } else if (array is DictionaryEntry[] dictEntryArray) { - Entry[] entries = _entries; + Entry[]? entries = _entries; for (int i = 0; i < _count; i++) { - if (entries[i].next >= -1) + if (entries![i].next >= -1) { dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value); } @@ -941,7 +951,7 @@ void ICollection.CopyTo(Array array, int index) } else { - object[] objects = array as object[]; + object[]? objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); @@ -950,12 +960,12 @@ void ICollection.CopyTo(Array array, int index) try { int count = _count; - Entry[] entries = _entries; + Entry[]? entries = _entries; for (int i = 0; i < count; i++) { - if (entries[i].next >= -1) + if (entries![i].next >= -1) { - objects[index++] = new KeyValuePair(entries[i].key, entries[i].value); + objects![index++] = new KeyValuePair(entries[i].key, entries[i].value); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } } } @@ -1013,7 +1023,7 @@ public void TrimExcess(int capacity) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); int newSize = HashHelpers.GetPrime(capacity); - Entry[] oldEntries = _entries; + Entry[]? oldEntries = _entries; int currentCapacity = oldEntries == null ? 0 : oldEntries.Length; if (newSize >= currentCapacity) return; @@ -1021,19 +1031,19 @@ public void TrimExcess(int capacity) int oldCount = _count; _version++; Initialize(newSize); - Entry[] entries = _entries; - int[] buckets = _buckets; + Entry[]? entries = _entries; + int[]? buckets = _buckets; int count = 0; for (int i = 0; i < oldCount; i++) { - uint hashCode = oldEntries[i].hashCode; + uint hashCode = oldEntries![i].hashCode; // At this point, we know we have entries. if (oldEntries[i].next >= -1) { - ref Entry entry = ref entries[count]; + ref Entry entry = ref entries![count]; entry = oldEntries[i]; uint bucket = hashCode % (uint)newSize; // Value in _buckets is 1-based - entry.next = buckets[bucket] - 1; + entry.next = buckets![bucket] - 1; // If we get here, we have entries, therefore buckets is not null. // Value in _buckets is 1-based buckets[bucket] = count + 1; count++; @@ -1055,7 +1065,8 @@ public void TrimExcess(int capacity) ICollection IDictionary.Values => (ICollection)Values; - object IDictionary.this[object key] + [DisallowNull] + object? IDictionary.this[object key] { get { @@ -1064,7 +1075,7 @@ object IDictionary.this[object key] int i = FindEntry((TKey)key); if (i >= 0) { - return _entries[i].value; + return _entries![i].value; } } return null; @@ -1079,10 +1090,10 @@ object IDictionary.this[object key] try { - TKey tempKey = (TKey)key; + TKey tempKey = (TKey)key!; // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected try { - this[tempKey] = (TValue)value; + this[tempKey] = (TValue)value!; } catch (InvalidCastException) { @@ -1105,7 +1116,7 @@ private static bool IsCompatibleKey(object key) return (key is TKey); } - void IDictionary.Add(object key, object value) + void IDictionary.Add(object key, object? value) { if (key == null) { @@ -1115,11 +1126,11 @@ void IDictionary.Add(object key, object value) try { - TKey tempKey = (TKey)key; + TKey tempKey = (TKey)key!; // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected try { - Add(tempKey, (TValue)value); + Add(tempKey, (TValue)value!); } catch (InvalidCastException) { @@ -1185,7 +1196,7 @@ public bool MoveNext() // dictionary.count+1 could be negative if dictionary.count is int.MaxValue while ((uint)_index < (uint)_dictionary._count) { - ref Entry entry = ref _dictionary._entries[_index++]; + ref Entry entry = ref _dictionary._entries![_index++]; if (entry.next >= -1) { @@ -1205,7 +1216,7 @@ public void Dispose() { } - object IEnumerator.Current + object? IEnumerator.Current { get { @@ -1262,7 +1273,7 @@ object IDictionaryEnumerator.Key } } - object IDictionaryEnumerator.Value + object? IDictionaryEnumerator.Value { get { @@ -1288,7 +1299,7 @@ public KeyCollection(Dictionary dictionary) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } - _dictionary = dictionary; + _dictionary = dictionary!; // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public Enumerator GetEnumerator() @@ -1301,21 +1312,21 @@ public void CopyTo(TKey[] array, int index) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (index < 0 || index > array.Length) + if (index < 0 || index > array!.Length) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } - if (array.Length - index < _dictionary.Count) + if (array!.Length - index < _dictionary.Count) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = _dictionary._count; - Entry[] entries = _dictionary._entries; + Entry[]? entries = _dictionary._entries; for (int i = 0; i < count; i++) { - if (entries[i].next >= -1) array[index++] = entries[i].key; + if (entries![i].next >= -1) array[index++] = entries[i].key; } } @@ -1348,7 +1359,7 @@ void ICollection.CopyTo(Array array, int index) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - if (array.Rank != 1) + if (array!.Rank != 1) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); if (array.GetLowerBound(0) != 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); @@ -1363,19 +1374,19 @@ void ICollection.CopyTo(Array array, int index) } else { - object[] objects = array as object[]; + object[]? objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = _dictionary._count; - Entry[] entries = _dictionary._entries; + Entry[]? entries = _dictionary._entries; try { for (int i = 0; i < count; i++) { - if (entries[i].next >= -1) objects[index++] = entries[i].key; + if (entries![i].next >= -1) objects![index++] = entries[i].key; // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } } catch (ArrayTypeMismatchException) @@ -1394,14 +1405,14 @@ public struct Enumerator : IEnumerator, IEnumerator private readonly Dictionary _dictionary; private int _index; private readonly int _version; - private TKey _currentKey; + [AllowNull, MaybeNull] private TKey _currentKey; internal Enumerator(Dictionary dictionary) { _dictionary = dictionary; _version = dictionary._version; _index = 0; - _currentKey = default; + _currentKey = default!; // TODO-NULLABLE: Remove ! when nullable attributes are respected } public void Dispose() @@ -1417,7 +1428,7 @@ public bool MoveNext() while ((uint)_index < (uint)_dictionary._count) { - ref Entry entry = ref _dictionary._entries[_index++]; + ref Entry entry = ref _dictionary._entries![_index++]; if (entry.next >= -1) { @@ -1427,13 +1438,13 @@ public bool MoveNext() } _index = _dictionary._count + 1; - _currentKey = default; + _currentKey = default!; // TODO-NULLABLE: Remove ! when nullable attributes are respected return false; } - public TKey Current => _currentKey; + public TKey Current => _currentKey!; - object IEnumerator.Current + object? IEnumerator.Current { get { @@ -1454,7 +1465,7 @@ void IEnumerator.Reset() } _index = 0; - _currentKey = default; + _currentKey = default!; // TODO-NULLABLE: Remove ! when nullable attributes are respected } } } @@ -1471,7 +1482,7 @@ public ValueCollection(Dictionary dictionary) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } - _dictionary = dictionary; + _dictionary = dictionary!; // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public Enumerator GetEnumerator() @@ -1484,7 +1495,7 @@ public void CopyTo(TValue[] array, int index) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (index < 0 || index > array.Length) + if ((uint)index > array!.Length) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } @@ -1495,10 +1506,10 @@ public void CopyTo(TValue[] array, int index) } int count = _dictionary._count; - Entry[] entries = _dictionary._entries; + Entry[]? entries = _dictionary._entries; for (int i = 0; i < count; i++) { - if (entries[i].next >= -1) array[index++] = entries[i].value; + if (entries![i].next >= -1) array[index++] = entries[i].value; } } @@ -1531,7 +1542,7 @@ void ICollection.CopyTo(Array array, int index) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - if (array.Rank != 1) + if (array!.Rank != 1) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); if (array.GetLowerBound(0) != 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); @@ -1546,19 +1557,19 @@ void ICollection.CopyTo(Array array, int index) } else { - object[] objects = array as object[]; + object[]? objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = _dictionary._count; - Entry[] entries = _dictionary._entries; + Entry[]? entries = _dictionary._entries; try { for (int i = 0; i < count; i++) { - if (entries[i].next >= -1) objects[index++] = entries[i].value; + if (entries![i].next >= -1) objects![index++] = entries[i].value!; // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } } catch (ArrayTypeMismatchException) @@ -1577,14 +1588,14 @@ public struct Enumerator : IEnumerator, IEnumerator private readonly Dictionary _dictionary; private int _index; private readonly int _version; - private TValue _currentValue; + [AllowNull, MaybeNull] private TValue _currentValue; internal Enumerator(Dictionary dictionary) { _dictionary = dictionary; _version = dictionary._version; _index = 0; - _currentValue = default; + _currentValue = default!; // TODO-NULLABLE: Remove ! when nullable attributes are respected } public void Dispose() @@ -1600,7 +1611,7 @@ public bool MoveNext() while ((uint)_index < (uint)_dictionary._count) { - ref Entry entry = ref _dictionary._entries[_index++]; + ref Entry entry = ref _dictionary._entries![_index++]; if (entry.next >= -1) { @@ -1609,13 +1620,13 @@ public bool MoveNext() } } _index = _dictionary._count + 1; - _currentValue = default; + _currentValue = default!; // TODO-NULLABLE: Remove ! when nullable attributes are respected return false; } - public TValue Current => _currentValue; + public TValue Current => _currentValue!; - object IEnumerator.Current + object? IEnumerator.Current { get { @@ -1635,7 +1646,7 @@ void IEnumerator.Reset() ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } _index = 0; - _currentValue = default; + _currentValue = default!; // TODO-NULLABLE: Remove ! when nullable attributes are respected } } } diff --git a/src/Common/src/CoreLib/System/Collections/Generic/EqualityComparer.cs b/src/Common/src/CoreLib/System/Collections/Generic/EqualityComparer.cs index 01204775e926..86a4e2a3b5bf 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/EqualityComparer.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/EqualityComparer.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.Serialization; @@ -13,10 +14,12 @@ public abstract partial class EqualityComparer : IEqualityComparer, IEquality { // public static EqualityComparer Default is runtime-specific - public abstract bool Equals(T x, T y); - public abstract int GetHashCode(T obj); + public abstract bool Equals([AllowNull] T x, [AllowNull] T y); + public abstract int GetHashCode([DisallowNull] T obj); - int IEqualityComparer.GetHashCode(object obj) +#pragma warning disable CS8617 // TODO-NULLABLE: Covariant parameter types (https://github.com/dotnet/roslyn/issues/30958) + int IEqualityComparer.GetHashCode(object? obj) +#pragma warning restore CS8617 { if (obj == null) return 0; if (obj is T) return GetHashCode((T)obj); @@ -24,7 +27,7 @@ int IEqualityComparer.GetHashCode(object obj) return 0; } - bool IEqualityComparer.Equals(object x, object y) + bool IEqualityComparer.Equals(object? x, object? y) { if (x == y) return true; if (x == null || y == null) return false; @@ -42,7 +45,7 @@ bool IEqualityComparer.Equals(object x, object y) public sealed partial class GenericEqualityComparer : EqualityComparer where T : IEquatable { [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override bool Equals(T x, T y) + public override bool Equals([AllowNull] T x, [AllowNull] T y) { if (x != null) { @@ -54,11 +57,11 @@ public override bool Equals(T x, T y) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override int GetHashCode(T obj) => obj?.GetHashCode() ?? 0; + public override int GetHashCode([DisallowNull] T obj) => obj?.GetHashCode() ?? 0; // Equals method for the comparer itself. // If in the future this type is made sealed, change the is check to obj != null && GetType() == obj.GetType(). - public override bool Equals(object obj) => + public override bool Equals(object? obj) => obj is GenericEqualityComparer; // If in the future this type is made sealed, change typeof(...) to GetType(). @@ -87,7 +90,7 @@ public override bool Equals(T? x, T? y) public override int GetHashCode(T? obj) => obj.GetHashCode(); // Equals method for the comparer itself. - public override bool Equals(object obj) => + public override bool Equals(object? obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => @@ -100,7 +103,7 @@ public override int GetHashCode() => public sealed partial class ObjectEqualityComparer : EqualityComparer { [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override bool Equals(T x, T y) + public override bool Equals([AllowNull] T x, [AllowNull] T y) { if (x != null) { @@ -112,10 +115,10 @@ public override bool Equals(T x, T y) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override int GetHashCode(T obj) => obj?.GetHashCode() ?? 0; + public override int GetHashCode([DisallowNull] T obj) => obj?.GetHashCode() ?? 0; // Equals method for the comparer itself. - public override bool Equals(object obj) => + public override bool Equals(object? obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => @@ -140,7 +143,7 @@ public override int GetHashCode(byte b) } // Equals method for the comparer itself. - public override bool Equals(object obj) => + public override bool Equals(object? obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => @@ -174,7 +177,7 @@ public override int GetHashCode(T obj) } // Equals method for the comparer itself. - public override bool Equals(object obj) => + public override bool Equals(object? obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => diff --git a/src/Common/src/CoreLib/System/Collections/Generic/IComparer.cs b/src/Common/src/CoreLib/System/Collections/Generic/IComparer.cs index 713d499cc846..064aa31ecd11 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/IComparer.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/IComparer.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics.CodeAnalysis; namespace System.Collections.Generic { @@ -15,6 +16,6 @@ public interface IComparer // value less than zero if x is less than y, zero if x is equal to y, or a // value greater than zero if x is greater than y. // - int Compare(T x, T y); + int Compare([AllowNull] T x, [AllowNull] T y); } } diff --git a/src/Common/src/CoreLib/System/Collections/Generic/IDictionary.cs b/src/Common/src/CoreLib/System/Collections/Generic/IDictionary.cs index 05677da3b2b7..a93ec25d9d77 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/IDictionary.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/IDictionary.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics.CodeAnalysis; namespace System.Collections.Generic { @@ -10,7 +11,7 @@ namespace System.Collections.Generic // Keys can be any non-null object. Values can be any object. // You can look up a value in an IDictionary via the default indexed // property, Items. - public interface IDictionary : ICollection> + public interface IDictionary : ICollection> where TKey : object { // Interfaces are not serializable // The Item property provides methods to read and edit entries @@ -45,6 +46,6 @@ ICollection Values // bool Remove(TKey key); - bool TryGetValue(TKey key, out TValue value); + bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value); } } diff --git a/src/Common/src/CoreLib/System/Collections/Generic/IDictionaryDebugView.cs b/src/Common/src/CoreLib/System/Collections/Generic/IDictionaryDebugView.cs index 4721642fee01..ff5b4ea5d1f8 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/IDictionaryDebugView.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/IDictionaryDebugView.cs @@ -6,7 +6,7 @@ namespace System.Collections.Generic { - internal sealed class IDictionaryDebugView + internal sealed class IDictionaryDebugView where K : object { private readonly IDictionary _dict; diff --git a/src/Common/src/CoreLib/System/Collections/Generic/IEnumerable.cs b/src/Common/src/CoreLib/System/Collections/Generic/IEnumerable.cs index d3ef9e86f76d..5548ffc19db0 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/IEnumerable.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/IEnumerable.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Collections.Generic { // Implement this interface if you need to support foreach semantics. diff --git a/src/Common/src/CoreLib/System/Collections/Generic/IEqualityComparer.cs b/src/Common/src/CoreLib/System/Collections/Generic/IEqualityComparer.cs index 7b983a9ccbe0..025d693e99a0 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/IEqualityComparer.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/IEqualityComparer.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable +using System.Diagnostics.CodeAnalysis; + namespace System.Collections.Generic { // The generic IEqualityComparer interface implements methods to if check two objects are equal @@ -10,8 +11,8 @@ namespace System.Collections.Generic // It is use in Dictionary class. public interface IEqualityComparer { - bool Equals(T x, T y); - int GetHashCode(T obj); // TODO-NULLABLE-GENERIC: This generally doesn't accept nulls. + bool Equals([AllowNull] T x, [AllowNull] T y); + int GetHashCode([DisallowNull] T obj); } } diff --git a/src/Common/src/CoreLib/System/Collections/Generic/IReadOnlyDictionary.cs b/src/Common/src/CoreLib/System/Collections/Generic/IReadOnlyDictionary.cs index 300b9966112b..48e9602eaad9 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/IReadOnlyDictionary.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/IReadOnlyDictionary.cs @@ -2,15 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +using System.Diagnostics.CodeAnalysis; namespace System.Collections.Generic { // Provides a read-only view of a generic dictionary. - public interface IReadOnlyDictionary : IReadOnlyCollection> + public interface IReadOnlyDictionary : IReadOnlyCollection> where TKey : object { bool ContainsKey(TKey key); - bool TryGetValue(TKey key, out TValue value); + bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value); TValue this[TKey key] { get; } IEnumerable Keys { get; } diff --git a/src/Common/src/CoreLib/System/Collections/Generic/KeyNotFoundException.cs b/src/Common/src/CoreLib/System/Collections/Generic/KeyNotFoundException.cs index 75f3e91c0739..35a81591b060 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/KeyNotFoundException.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/KeyNotFoundException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System.Collections.Generic diff --git a/src/Common/src/CoreLib/System/Collections/Generic/KeyValuePair.cs b/src/Common/src/CoreLib/System/Collections/Generic/KeyValuePair.cs index 82c786d407c3..8a35aa184781 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/KeyValuePair.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/KeyValuePair.cs @@ -19,7 +19,7 @@ public static KeyValuePair Create(TKey key, TValue v /// /// Used by KeyValuePair.ToString to reduce generic code /// - internal static string PairToString(object key, object value) + internal static string PairToString(object? key, object? value) { StringBuilder s = StringBuilderCache.Acquire(); s.Append('['); diff --git a/src/Common/src/CoreLib/System/Collections/Generic/List.cs b/src/Common/src/CoreLib/System/Collections/Generic/List.cs index 59dcd9344b6d..4a272244f7ad 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/List.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/List.cs @@ -4,6 +4,7 @@ using System.Collections.ObjectModel; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; @@ -80,7 +81,7 @@ public List(IEnumerable collection) { _size = 0; _items = s_emptyArray; - using (IEnumerator en = collection.GetEnumerator()) + using (IEnumerator en = collection!.GetEnumerator()) { while (en.MoveNext()) { @@ -166,14 +167,14 @@ public T this[int index] } } - private static bool IsCompatibleObject(object value) + private static bool IsCompatibleObject(object? value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable. // Note that default(T) is not equal to null for value types except when T is Nullable. - return ((value is T) || (value == null && default(T) == null)); + return ((value is T) || (value == null && default(T)! == null)); // default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) } - object IList.this[int index] + object? IList.this[int index] { get { @@ -185,7 +186,7 @@ object IList.this[int index] try { - this[index] = (T)value; + this[index] = (T)value!; } catch (InvalidCastException) { @@ -225,13 +226,13 @@ private void AddWithResize(T item) _items[size] = item; } - int IList.Add(object item) + int IList.Add(object? item) { ThrowHelper.IfNullAndNullsAreIllegalThenThrow(item, ExceptionArgument.item); try { - Add((T)item); + Add((T)item!); } catch (InvalidCastException) { @@ -271,7 +272,7 @@ public ReadOnlyCollection AsReadOnly() // The method uses the Array.BinarySearch method to perform the // search. // - public int BinarySearch(int index, int count, T item, IComparer comparer) + public int BinarySearch(int index, int count, T item, IComparer? comparer) { if (index < 0) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); @@ -286,7 +287,7 @@ public int BinarySearch(int index, int count, T item, IComparer comparer) public int BinarySearch(T item) => BinarySearch(0, Count, item, null); - public int BinarySearch(T item, IComparer comparer) + public int BinarySearch(T item, IComparer? comparer) => BinarySearch(0, Count, item, comparer); // Clears the contents of List. @@ -326,11 +327,11 @@ public bool Contains(T item) return _size != 0 && IndexOf(item) != -1; } - bool IList.Contains(object item) + bool IList.Contains(object? item) { if (IsCompatibleObject(item)) { - return Contains((T)item); + return Contains((T)item!); } return false; } @@ -345,7 +346,7 @@ public List ConvertAll(Converter converter) List list = new List(_size); for (int i = 0; i < _size; i++) { - list._items[i] = converter(_items[i]); + list._items[i] = converter!(_items[i]); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } list._size = _size; return list; @@ -368,7 +369,7 @@ void ICollection.CopyTo(Array array, int arrayIndex) try { // Array.Copy will check for NULL. - Array.Copy(_items, 0, array, arrayIndex, _size); + Array.Copy(_items, 0, array!, arrayIndex, _size); } catch (ArrayTypeMismatchException) { @@ -418,6 +419,7 @@ private void EnsureCapacity(int min) public bool Exists(Predicate match) => FindIndex(match) != -1; + [return: MaybeNull] public T Find(Predicate match) { if (match == null) @@ -427,12 +429,12 @@ public T Find(Predicate match) for (int i = 0; i < _size; i++) { - if (match(_items[i])) + if (match!(_items[i])) { return _items[i]; } } - return default; + return default!; } public List FindAll(Predicate match) @@ -445,7 +447,7 @@ public List FindAll(Predicate match) List list = new List(); for (int i = 0; i < _size; i++) { - if (match(_items[i])) + if (match!(_items[i])) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { list.Add(_items[i]); } @@ -479,11 +481,12 @@ public int FindIndex(int startIndex, int count, Predicate match) int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) { - if (match(_items[i])) return i; + if (match!(_items[i])) return i; } return -1; } + [return: MaybeNull] public T FindLast(Predicate match) { if (match == null) @@ -493,12 +496,12 @@ public T FindLast(Predicate match) for (int i = _size - 1; i >= 0; i--) { - if (match(_items[i])) + if (match!(_items[i])) { return _items[i]; } } - return default; + return default!; } public int FindLastIndex(Predicate match) @@ -540,7 +543,7 @@ public int FindLastIndex(int startIndex, int count, Predicate match) int endIndex = startIndex - count; for (int i = startIndex; i > endIndex; i--) { - if (match(_items[i])) + if (match!(_items[i])) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { return i; } @@ -563,7 +566,7 @@ public void ForEach(Action action) { break; } - action(_items[i]); + action!(_items[i]); } if (version != _version) @@ -619,11 +622,11 @@ public List GetRange(int index, int count) public int IndexOf(T item) => Array.IndexOf(_items, item, 0, _size); - int IList.IndexOf(object item) + int IList.IndexOf(object? item) { if (IsCompatibleObject(item)) { - return IndexOf((T)item); + return IndexOf((T)item!); } return -1; } @@ -685,13 +688,13 @@ public void Insert(int index, T item) _version++; } - void IList.Insert(int index, object item) + void IList.Insert(int index, object? item) { ThrowHelper.IfNullAndNullsAreIllegalThenThrow(item, ExceptionArgument.item); try { - Insert(index, (T)item); + Insert(index, (T)item!); } catch (InvalidCastException) { @@ -744,7 +747,7 @@ public void InsertRange(int index, IEnumerable collection) } else { - using (IEnumerator en = collection.GetEnumerator()) + using (IEnumerator en = collection!.GetEnumerator()) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { while (en.MoveNext()) { @@ -844,11 +847,11 @@ public bool Remove(T item) return false; } - void IList.Remove(object item) + void IList.Remove(object? item) { if (IsCompatibleObject(item)) { - Remove((T)item); + Remove((T)item!); } } @@ -864,14 +867,14 @@ public int RemoveAll(Predicate match) int freeIndex = 0; // the first free slot in items array // Find the first item which needs to be removed. - while (freeIndex < _size && !match(_items[freeIndex])) freeIndex++; + while (freeIndex < _size && !match!(_items[freeIndex])) freeIndex++; // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected if (freeIndex >= _size) return 0; int current = freeIndex + 1; while (current < _size) { // Find the first item which needs to be kept. - while (current < _size && match(_items[current])) current++; + while (current < _size && match!(_items[current])) current++; if (current < _size) { @@ -906,7 +909,7 @@ public void RemoveAt(int index) } if (RuntimeHelpers.IsReferenceOrContainsReferences()) { - _items[_size] = default; + _items[_size] = default!; } _version++; } @@ -981,7 +984,7 @@ public void Sort() // Sorts the elements in this list. Uses Array.Sort with the // provided comparer. - public void Sort(IComparer comparer) + public void Sort(IComparer? comparer) => Sort(0, Count, comparer); // Sorts the elements in a section of this list. The sort compares the @@ -992,7 +995,7 @@ public void Sort(IComparer comparer) // // This method uses the Array.Sort method to sort the elements. // - public void Sort(int index, int count, IComparer comparer) + public void Sort(int index, int count, IComparer? comparer) { if (index < 0) { @@ -1023,7 +1026,7 @@ public void Sort(Comparison comparison) if (_size > 1) { - ArraySortHelper.Sort(_items, 0, _size, comparison); + ArraySortHelper.Sort(_items, 0, _size, comparison!); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } _version++; } @@ -1069,7 +1072,7 @@ public bool TrueForAll(Predicate match) for (int i = 0; i < _size; i++) { - if (!match(_items[i])) + if (!match!(_items[i])) { return false; } @@ -1082,14 +1085,14 @@ public struct Enumerator : IEnumerator, IEnumerator private readonly List _list; private int _index; private readonly int _version; - private T _current; + [AllowNull, MaybeNull] private T _current; internal Enumerator(List list) { _list = list; _index = 0; _version = list._version; - _current = default; + _current = default!; // TODO-NULLABLE: Remove ! when nullable attributes are respected } public void Dispose() @@ -1117,13 +1120,13 @@ private bool MoveNextRare() } _index = _list._size + 1; - _current = default; + _current = default!; // TODO-NULLABLE: Remove ! when nullable attributes are respected return false; } - public T Current => _current; + public T Current => _current!; - object IEnumerator.Current + object? IEnumerator.Current { get { @@ -1143,7 +1146,7 @@ void IEnumerator.Reset() } _index = 0; - _current = default; + _current = default!; // TODO-NULLABLE: Remove ! when nullable attributes are respected } } } diff --git a/src/Common/src/CoreLib/System/Collections/Generic/NonRandomizedStringEqualityComparer.cs b/src/Common/src/CoreLib/System/Collections/Generic/NonRandomizedStringEqualityComparer.cs index 91b782061761..f042a6bb7b55 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/NonRandomizedStringEqualityComparer.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/NonRandomizedStringEqualityComparer.cs @@ -12,18 +12,18 @@ namespace System.Collections.Generic // randomized string hashing. [Serializable] // Required for compatibility with .NET Core 2.0 as we exposed the NonRandomizedStringEqualityComparer inside the serialization blob // Needs to be public to support binary serialization compatibility - public sealed class NonRandomizedStringEqualityComparer : EqualityComparer, ISerializable + public sealed class NonRandomizedStringEqualityComparer : EqualityComparer, ISerializable { - internal static new IEqualityComparer Default { get; } = new NonRandomizedStringEqualityComparer(); + internal static new IEqualityComparer Default { get; } = new NonRandomizedStringEqualityComparer(); private NonRandomizedStringEqualityComparer() { } // This is used by the serialization engine. private NonRandomizedStringEqualityComparer(SerializationInfo information, StreamingContext context) { } - public sealed override bool Equals(string x, string y) => string.Equals(x, y); + public sealed override bool Equals(string? x, string? y) => string.Equals(x, y); - public sealed override int GetHashCode(string obj) => obj?.GetNonRandomizedHashCode() ?? 0; + public sealed override int GetHashCode(string? obj) => obj?.GetNonRandomizedHashCode() ?? 0; public void GetObjectData(SerializationInfo info, StreamingContext context) { diff --git a/src/Common/src/CoreLib/System/Collections/Generic/ValueListBuilder.cs b/src/Common/src/CoreLib/System/Collections/Generic/ValueListBuilder.cs index aea6052f030a..cce86c23e4ef 100644 --- a/src/Common/src/CoreLib/System/Collections/Generic/ValueListBuilder.cs +++ b/src/Common/src/CoreLib/System/Collections/Generic/ValueListBuilder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -11,7 +12,7 @@ namespace System.Collections.Generic internal ref partial struct ValueListBuilder { private Span _span; - private T[] _arrayFromPool; + private T[]? _arrayFromPool; private int _pos; public ValueListBuilder(Span initialSpan) @@ -74,7 +75,7 @@ private void Grow() bool success = _span.TryCopyTo(array); Debug.Assert(success); - T[] toReturn = _arrayFromPool; + T[]? toReturn = _arrayFromPool; _span = _arrayFromPool = array; if (toReturn != null) { diff --git a/src/Common/src/CoreLib/System/Collections/HashHelpers.SerializationInfoTable.cs b/src/Common/src/CoreLib/System/Collections/HashHelpers.SerializationInfoTable.cs index d91dfd878e35..64cf029d1c70 100644 --- a/src/Common/src/CoreLib/System/Collections/HashHelpers.SerializationInfoTable.cs +++ b/src/Common/src/CoreLib/System/Collections/HashHelpers.SerializationInfoTable.cs @@ -13,7 +13,7 @@ namespace System.Collections { internal static partial class HashHelpers { - private static ConditionalWeakTable s_serializationInfoTable; + private static ConditionalWeakTable? s_serializationInfoTable; public static ConditionalWeakTable SerializationInfoTable { @@ -22,8 +22,8 @@ public static ConditionalWeakTable SerializationInfoT if (s_serializationInfoTable == null) Interlocked.CompareExchange(ref s_serializationInfoTable, new ConditionalWeakTable(), null); - return s_serializationInfoTable; + return s_serializationInfoTable!; // TODO-NULLABLE: Remove ! when compiler specially-recognizes CompareExchange for nullability } } } -} \ No newline at end of file +} diff --git a/src/Common/src/CoreLib/System/Collections/HashHelpers.cs b/src/Common/src/CoreLib/System/Collections/HashHelpers.cs index ba2c75c89c88..491a0ec6b9ab 100644 --- a/src/Common/src/CoreLib/System/Collections/HashHelpers.cs +++ b/src/Common/src/CoreLib/System/Collections/HashHelpers.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - using System.Diagnostics; namespace System.Collections diff --git a/src/Common/src/CoreLib/System/Collections/Hashtable.cs b/src/Common/src/CoreLib/System/Collections/Hashtable.cs index 5c562126307d..06e57b7adaeb 100644 --- a/src/Common/src/CoreLib/System/Collections/Hashtable.cs +++ b/src/Common/src/CoreLib/System/Collections/Hashtable.cs @@ -127,12 +127,12 @@ the hash table. // This cannot be serialized private struct bucket { - public object key; - public object val; + public object? key; + public object? val; public int hash_coll; // Store hash code; sign bit means there was a collision. } - private bucket[] _buckets; + private bucket[] _buckets = null!; // The total number of entries in the hash table. private int _count; @@ -146,13 +146,13 @@ private struct bucket private volatile int _version; private volatile bool _isWriterInProgress; - private ICollection _keys; - private ICollection _values; + private ICollection? _keys; + private ICollection? _values; - private IEqualityComparer _keycomparer; + private IEqualityComparer? _keycomparer; [Obsolete("Please use EqualityComparer property.")] - protected IHashCodeProvider hcp + protected IHashCodeProvider? hcp { get { @@ -178,7 +178,7 @@ protected IHashCodeProvider hcp } else if (_keycomparer == null) { - _keycomparer = new CompatibleComparer(value, (IComparer)null); + _keycomparer = new CompatibleComparer(value, (IComparer?)null); } else { @@ -188,7 +188,7 @@ protected IHashCodeProvider hcp } [Obsolete("Please use KeyComparer properties.")] - protected IComparer comparer + protected IComparer? comparer { get { @@ -214,7 +214,7 @@ protected IComparer comparer } else if (_keycomparer == null) { - _keycomparer = new CompatibleComparer((IHashCodeProvider)null, value); + _keycomparer = new CompatibleComparer((IHashCodeProvider?)null, value); } else { @@ -224,7 +224,7 @@ protected IComparer comparer } - protected IEqualityComparer EqualityComparer + protected IEqualityComparer? EqualityComparer { get { @@ -290,28 +290,28 @@ public Hashtable(int capacity, float loadFactor) Debug.Assert(_loadsize < hashsize, "Invalid hashtable loadsize!"); } - public Hashtable(int capacity, float loadFactor, IEqualityComparer equalityComparer) : this(capacity, loadFactor) + public Hashtable(int capacity, float loadFactor, IEqualityComparer? equalityComparer) : this(capacity, loadFactor) { _keycomparer = equalityComparer; } [Obsolete("Please use Hashtable(IEqualityComparer) instead.")] - public Hashtable(IHashCodeProvider hcp, IComparer comparer) + public Hashtable(IHashCodeProvider? hcp, IComparer? comparer) : this(0, 1.0f, hcp, comparer) { } - public Hashtable(IEqualityComparer equalityComparer) : this(0, 1.0f, equalityComparer) + public Hashtable(IEqualityComparer? equalityComparer) : this(0, 1.0f, equalityComparer) { } [Obsolete("Please use Hashtable(int, IEqualityComparer) instead.")] - public Hashtable(int capacity, IHashCodeProvider hcp, IComparer comparer) + public Hashtable(int capacity, IHashCodeProvider? hcp, IComparer? comparer) : this(capacity, 1.0f, hcp, comparer) { } - public Hashtable(int capacity, IEqualityComparer equalityComparer) + public Hashtable(int capacity, IEqualityComparer? equalityComparer) : this(capacity, 1.0f, equalityComparer) { } @@ -327,23 +327,23 @@ public Hashtable(IDictionary d) : this(d, 1.0f) // dictionary. The hashtable is created with the given load factor. // public Hashtable(IDictionary d, float loadFactor) - : this(d, loadFactor, (IEqualityComparer)null) + : this(d, loadFactor, (IEqualityComparer?)null) { } [Obsolete("Please use Hashtable(IDictionary, IEqualityComparer) instead.")] - public Hashtable(IDictionary d, IHashCodeProvider hcp, IComparer comparer) + public Hashtable(IDictionary d, IHashCodeProvider? hcp, IComparer? comparer) : this(d, 1.0f, hcp, comparer) { } - public Hashtable(IDictionary d, IEqualityComparer equalityComparer) + public Hashtable(IDictionary d, IEqualityComparer? equalityComparer) : this(d, 1.0f, equalityComparer) { } [Obsolete("Please use Hashtable(int, float, IEqualityComparer) instead.")] - public Hashtable(int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer) + public Hashtable(int capacity, float loadFactor, IHashCodeProvider? hcp, IComparer? comparer) : this(capacity, loadFactor) { if (hcp != null || comparer != null) @@ -353,7 +353,7 @@ public Hashtable(int capacity, float loadFactor, IHashCodeProvider hcp, ICompare } [Obsolete("Please use Hashtable(IDictionary, float, IEqualityComparer) instead.")] - public Hashtable(IDictionary d, float loadFactor, IHashCodeProvider hcp, IComparer comparer) + public Hashtable(IDictionary d, float loadFactor, IHashCodeProvider? hcp, IComparer? comparer) : this((d != null ? d.Count : 0), loadFactor, hcp, comparer) { if (d == null) @@ -364,7 +364,7 @@ public Hashtable(IDictionary d, float loadFactor, IHashCodeProvider hcp, ICompar Add(e.Key, e.Value); } - public Hashtable(IDictionary d, float loadFactor, IEqualityComparer equalityComparer) + public Hashtable(IDictionary d, float loadFactor, IEqualityComparer? equalityComparer) : this((d != null ? d.Count : 0), loadFactor, equalityComparer) { if (d == null) @@ -422,7 +422,7 @@ private uint InitHash(object key, int hashsize, out uint seed, out uint incr) // ArgumentException is thrown if the key is null or if the key is already // present in the hashtable. // - public virtual void Add(object key, object value) + public virtual void Add(object key, object? value) { Insert(key, value, true); } @@ -464,7 +464,7 @@ public virtual object Clone() while (bucket > 0) { bucket--; - object keyv = lbuckets[bucket].key; + object? keyv = lbuckets[bucket].key; if ((keyv != null) && (keyv != lbuckets)) { ht[keyv] = lbuckets[bucket].val; @@ -522,7 +522,7 @@ public virtual bool ContainsKey(object key) // search and is thus be substantially slower than the ContainsKey // method. // - public virtual bool ContainsValue(object value) + public virtual bool ContainsValue(object? value) { if (value == null) { @@ -536,7 +536,7 @@ public virtual bool ContainsValue(object value) { for (int i = _buckets.Length; --i >= 0;) { - object val = _buckets[i].val; + object? val = _buckets[i].val; if (val != null && val.Equals(value)) return true; } @@ -555,7 +555,7 @@ private void CopyKeys(Array array, int arrayIndex) bucket[] lbuckets = _buckets; for (int i = lbuckets.Length; --i >= 0;) { - object keyv = lbuckets[i].key; + object? keyv = lbuckets[i].key; if ((keyv != null) && (keyv != _buckets)) { array.SetValue(keyv, arrayIndex++); @@ -574,7 +574,7 @@ private void CopyEntries(Array array, int arrayIndex) bucket[] lbuckets = _buckets; for (int i = lbuckets.Length; --i >= 0;) { - object keyv = lbuckets[i].key; + object? keyv = lbuckets[i].key; if ((keyv != null) && (keyv != _buckets)) { DictionaryEntry entry = new DictionaryEntry(keyv, lbuckets[i].val); @@ -610,7 +610,7 @@ internal virtual KeyValuePairs[] ToKeyValuePairsArray() bucket[] lbuckets = _buckets; for (int i = lbuckets.Length; --i >= 0;) { - object keyv = lbuckets[i].key; + object? keyv = lbuckets[i].key; if ((keyv != null) && (keyv != _buckets)) { array[index++] = new KeyValuePairs(keyv, lbuckets[i].val); @@ -632,7 +632,7 @@ private void CopyValues(Array array, int arrayIndex) bucket[] lbuckets = _buckets; for (int i = lbuckets.Length; --i >= 0;) { - object keyv = lbuckets[i].key; + object? keyv = lbuckets[i].key; if ((keyv != null) && (keyv != _buckets)) { array.SetValue(lbuckets[i].val, arrayIndex++); @@ -643,7 +643,7 @@ private void CopyValues(Array array, int arrayIndex) // Returns the value associated with the given key. If an entry with the // given key is not found, the returned value is null. // - public virtual object this[object key] + public virtual object? this[object key] { get { @@ -826,7 +826,7 @@ public virtual bool IsSynchronized // instance in the constructor, this method will call comparer.Compare(item, key). // Otherwise, it will call item.Equals(key). // - protected virtual bool KeyEquals(object item, object key) + protected virtual bool KeyEquals(object? item, object key) { Debug.Assert(key != null, "key can't be null here!"); if (object.ReferenceEquals(_buckets, item)) @@ -884,7 +884,7 @@ public virtual ICollection Values // Inserts an entry into this hashtable. This method is called from the Set // and Add methods. If the add parameter is true and the given key already // exists in the hashtable, an exception is thrown. - private void Insert(object key, object nvalue, bool add) + private void Insert(object key, object? nvalue, bool add) { if (key == null) { @@ -997,7 +997,7 @@ private void Insert(object key, object nvalue, bool add) throw new InvalidOperationException(SR.InvalidOperation_HashInsertFailed); } - private void putEntry(bucket[] newBuckets, object key, object nvalue, int hashcode) + private void putEntry(bucket[] newBuckets, object key, object? nvalue, int hashcode) { Debug.Assert(hashcode >= 0, "hashcode >= 0"); // make sure collision bit (sign bit) wasn't set. @@ -1114,7 +1114,7 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte // Also, if the Hashtable is using randomized hashing, serialize the old // view of the _keycomparer so perevious frameworks don't see the new types #pragma warning disable 618 - IEqualityComparer keyComparerForSerilization = _keycomparer; + IEqualityComparer? keyComparerForSerilization = _keycomparer; if (keyComparerForSerilization == null) { @@ -1123,7 +1123,7 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte } else if (keyComparerForSerilization is CompatibleComparer) { - CompatibleComparer c = keyComparerForSerilization as CompatibleComparer; + CompatibleComparer c = (keyComparerForSerilization as CompatibleComparer)!; info.AddValue(ComparerName, c.Comparer, typeof(IComparer)); info.AddValue(HashCodeProviderName, c.HashCodeProvider, typeof(IHashCodeProvider)); } @@ -1170,14 +1170,14 @@ public virtual void OnDeserialization(object sender) } int hashsize = 0; - IComparer c = null; + IComparer? c = null; #pragma warning disable 618 - IHashCodeProvider hcp = null; + IHashCodeProvider? hcp = null; #pragma warning restore 618 - object[] serKeys = null; - object[] serValues = null; + object[]? serKeys = null; + object?[]? serValues = null; SerializationInfoEnumerator enumerator = siInfo.GetEnumerator(); @@ -1192,21 +1192,21 @@ public virtual void OnDeserialization(object sender) hashsize = siInfo.GetInt32(HashSizeName); break; case KeyComparerName: - _keycomparer = (IEqualityComparer)siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer)); + _keycomparer = (IEqualityComparer?)siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer)); break; case ComparerName: - c = (IComparer)siInfo.GetValue(ComparerName, typeof(IComparer)); + c = (IComparer?)siInfo.GetValue(ComparerName, typeof(IComparer)); break; case HashCodeProviderName: #pragma warning disable 618 - hcp = (IHashCodeProvider)siInfo.GetValue(HashCodeProviderName, typeof(IHashCodeProvider)); + hcp = (IHashCodeProvider?)siInfo.GetValue(HashCodeProviderName, typeof(IHashCodeProvider)); #pragma warning restore 618 break; case KeysName: - serKeys = (object[])siInfo.GetValue(KeysName, typeof(object[])); + serKeys = (object[]?)siInfo.GetValue(KeysName, typeof(object[])); break; case ValuesName: - serValues = (object[])siInfo.GetValue(ValuesName, typeof(object[])); + serValues = (object?[]?)siInfo.GetValue(ValuesName, typeof(object[])); break; } } @@ -1377,7 +1377,7 @@ public override bool IsSynchronized get { return true; } } - public override object this[object key] + public override object? this[object key] { get { @@ -1397,7 +1397,7 @@ public override object SyncRoot get { return _table.SyncRoot; } } - public override void Add(object key, object value) + public override void Add(object key, object? value) { lock (_table.SyncRoot) { @@ -1427,7 +1427,7 @@ public override bool ContainsKey(object key) return _table.ContainsKey(key); } - public override bool ContainsValue(object key) + public override bool ContainsValue(object? key) { lock (_table.SyncRoot) { @@ -1515,8 +1515,8 @@ private class HashtableEnumerator : IDictionaryEnumerator, ICloneable private int _version; private bool _current; private int _getObjectRetType; // What should GetObject return? - private object _currentKey; - private object _currentValue; + private object? _currentKey; + private object? _currentValue; internal const int Keys = 1; internal const int Values = 2; @@ -1539,7 +1539,7 @@ public virtual object Key { if (_current == false) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); - return _currentKey; + return _currentKey!; } } @@ -1550,7 +1550,7 @@ public virtual bool MoveNext() while (_bucket > 0) { _bucket--; - object keyv = _hashtable._buckets[_bucket].key; + object? keyv = _hashtable._buckets[_bucket].key; if ((keyv != null) && (keyv != _hashtable._buckets)) { _currentKey = keyv; @@ -1569,12 +1569,12 @@ public virtual DictionaryEntry Entry { if (_current == false) throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); - return new DictionaryEntry(_currentKey, _currentValue); + return new DictionaryEntry(_currentKey!, _currentValue); } } - public virtual object Current + public virtual object? Current { get { @@ -1586,11 +1586,11 @@ public virtual object Current else if (_getObjectRetType == Values) return _currentValue; else - return new DictionaryEntry(_currentKey, _currentValue); + return new DictionaryEntry(_currentKey!, _currentValue); } } - public virtual object Value + public virtual object? Value { get { diff --git a/src/Common/src/CoreLib/System/Collections/IComparer.cs b/src/Common/src/CoreLib/System/Collections/IComparer.cs index 46c12ff46a9a..877e9b40e9f7 100644 --- a/src/Common/src/CoreLib/System/Collections/IComparer.cs +++ b/src/Common/src/CoreLib/System/Collections/IComparer.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Collections { // The IComparer interface implements a method that compares two objects. It is diff --git a/src/Common/src/CoreLib/System/Collections/IDictionary.cs b/src/Common/src/CoreLib/System/Collections/IDictionary.cs index b077c9192754..551250062726 100644 --- a/src/Common/src/CoreLib/System/Collections/IDictionary.cs +++ b/src/Common/src/CoreLib/System/Collections/IDictionary.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +using System.Diagnostics.CodeAnalysis; namespace System.Collections { @@ -15,46 +15,36 @@ public interface IDictionary : ICollection // Interfaces are not serializable // The Item property provides methods to read and edit entries // in the Dictionary. - object this[object key] + [DisallowNull] + object? this[object key] { get; set; } // Returns a collections of the keys in this dictionary. - ICollection Keys - { - get; - } + ICollection Keys {get; } // Returns a collections of the values in this dictionary. - ICollection Values - { - get; - } + ICollection Values { get; } // Returns whether this dictionary contains a particular key. - // bool Contains(object key); // Adds a key-value pair to the dictionary. - // - void Add(object key, object value); + void Add(object key, object? value); // Removes all pairs from the dictionary. void Clear(); - bool IsReadOnly - { get; } + bool IsReadOnly { get; } - bool IsFixedSize - { get; } + bool IsFixedSize { get; } // Returns an IDictionaryEnumerator for this dictionary. new IDictionaryEnumerator GetEnumerator(); // Removes a particular key from the dictionary. - // void Remove(object key); } } diff --git a/src/Common/src/CoreLib/System/Collections/IDictionaryEnumerator.cs b/src/Common/src/CoreLib/System/Collections/IDictionaryEnumerator.cs index 0cf6aaa1545d..2c4805ee3630 100644 --- a/src/Common/src/CoreLib/System/Collections/IDictionaryEnumerator.cs +++ b/src/Common/src/CoreLib/System/Collections/IDictionaryEnumerator.cs @@ -50,7 +50,7 @@ object Key // to GetValue with no intervening calls to GetNext will // return the same object. // - object Value + object? Value { get; } diff --git a/src/Common/src/CoreLib/System/Collections/IEnumerable.cs b/src/Common/src/CoreLib/System/Collections/IEnumerable.cs index 5ca523f69249..e787bde2ee6b 100644 --- a/src/Common/src/CoreLib/System/Collections/IEnumerable.cs +++ b/src/Common/src/CoreLib/System/Collections/IEnumerable.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; namespace System.Collections diff --git a/src/Common/src/CoreLib/System/Collections/IEnumerator.cs b/src/Common/src/CoreLib/System/Collections/IEnumerator.cs index 83d2064dff8f..0d2ccb946635 100644 --- a/src/Common/src/CoreLib/System/Collections/IEnumerator.cs +++ b/src/Common/src/CoreLib/System/Collections/IEnumerator.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/Collections/IEqualityComparer.cs b/src/Common/src/CoreLib/System/Collections/IEqualityComparer.cs index 9b5476896ce6..cc60060279dd 100644 --- a/src/Common/src/CoreLib/System/Collections/IEqualityComparer.cs +++ b/src/Common/src/CoreLib/System/Collections/IEqualityComparer.cs @@ -2,15 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; - namespace System.Collections { // An IEqualityComparer is a mechanism to consume custom performant comparison infrastructure // that can be consumed by some of the common collections. public interface IEqualityComparer { - bool Equals(object x, object y); + bool Equals(object? x, object? y); int GetHashCode(object obj); } } diff --git a/src/Common/src/CoreLib/System/Collections/IList.cs b/src/Common/src/CoreLib/System/Collections/IList.cs index 25d3b1922690..5a709e25d577 100644 --- a/src/Common/src/CoreLib/System/Collections/IList.cs +++ b/src/Common/src/CoreLib/System/Collections/IList.cs @@ -12,7 +12,7 @@ namespace System.Collections public interface IList : ICollection { // The Item property provides methods to read and edit entries in the List. - object this[int index] + object? this[int index] { get; set; @@ -22,10 +22,10 @@ object this[int index] // implementation-dependent, so while ArrayList may always insert // in the last available location, a SortedList most likely would not. // The return value is the position the new element was inserted in. - int Add(object value); + int Add(object? value); // Returns whether the list contains a particular item. - bool Contains(object value); + bool Contains(object? value); // Removes all items from the list. void Clear(); @@ -42,16 +42,16 @@ bool IsFixedSize // Returns the index of a particular item, if it is in the list. // Returns -1 if the item isn't in the list. - int IndexOf(object value); + int IndexOf(object? value); // Inserts value into the list at position index. // index must be non-negative and less than or equal to the // number of elements in the list. If index equals the number // of items in the list, then value is appended to the end. - void Insert(int index, object value); + void Insert(int index, object? value); // Removes an item from the list. - void Remove(object value); + void Remove(object? value); // Removes the item at position index. void RemoveAt(int index); diff --git a/src/Common/src/CoreLib/System/Collections/IStructuralComparable.cs b/src/Common/src/CoreLib/System/Collections/IStructuralComparable.cs index 9041e0d5ff2e..1849e367c41e 100644 --- a/src/Common/src/CoreLib/System/Collections/IStructuralComparable.cs +++ b/src/Common/src/CoreLib/System/Collections/IStructuralComparable.cs @@ -8,6 +8,6 @@ namespace System.Collections { public interface IStructuralComparable { - int CompareTo(object other, IComparer comparer); + int CompareTo(object? other, IComparer comparer); } } diff --git a/src/Common/src/CoreLib/System/Collections/IStructuralEquatable.cs b/src/Common/src/CoreLib/System/Collections/IStructuralEquatable.cs index 9fba68377cc4..a244e8417a51 100644 --- a/src/Common/src/CoreLib/System/Collections/IStructuralEquatable.cs +++ b/src/Common/src/CoreLib/System/Collections/IStructuralEquatable.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Collections { public interface IStructuralEquatable diff --git a/src/Common/src/CoreLib/System/Collections/KeyValuePairs.cs b/src/Common/src/CoreLib/System/Collections/KeyValuePairs.cs index 9ec6365b92f7..4bbca18c54a8 100644 --- a/src/Common/src/CoreLib/System/Collections/KeyValuePairs.cs +++ b/src/Common/src/CoreLib/System/Collections/KeyValuePairs.cs @@ -11,6 +11,7 @@ ** ===========================================================*/ +#nullable enable using System.Diagnostics; namespace System.Collections @@ -22,9 +23,9 @@ internal class KeyValuePairs private readonly object _key; [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private readonly object _value; + private readonly object? _value; - public KeyValuePairs(object key, object value) + public KeyValuePairs(object key, object? value) { _value = value; _key = key; diff --git a/src/Common/src/CoreLib/System/Collections/ListDictionaryInternal.cs b/src/Common/src/CoreLib/System/Collections/ListDictionaryInternal.cs index 1bc61db2a377..b6b546297f8d 100644 --- a/src/Common/src/CoreLib/System/Collections/ListDictionaryInternal.cs +++ b/src/Common/src/CoreLib/System/Collections/ListDictionaryInternal.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ - namespace System.Collections { /// This is a simple implementation of IDictionary using a singly linked list. This @@ -23,7 +22,7 @@ namespace System.Collections // Needs to be public to support binary serialization compatibility public class ListDictionaryInternal : IDictionary { - private DictionaryNode head; // Do not rename (binary serialization) + private DictionaryNode? head; // Do not rename (binary serialization) private int version; // Do not rename (binary serialization) private int count; // Do not rename (binary serialization) @@ -31,7 +30,7 @@ public ListDictionaryInternal() { } - public object this[object key] + public object? this[object key] { get { @@ -39,7 +38,7 @@ public object this[object key] { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } - DictionaryNode node = head; + DictionaryNode? node = head; while (node != null) { @@ -60,8 +59,8 @@ public object this[object key] version++; - DictionaryNode last = null; - DictionaryNode node; + DictionaryNode? last = null; + DictionaryNode? node; for (node = head; node != null; node = node.next) { if (node.key.Equals(key)) @@ -142,7 +141,7 @@ public ICollection Values } } - public void Add(object key, object value) + public void Add(object key, object? value) { if (key == null) { @@ -151,8 +150,8 @@ public void Add(object key, object value) version++; - DictionaryNode last = null; - DictionaryNode node; + DictionaryNode? last = null; + DictionaryNode? node; for (node = head; node != null; node = node.next) { if (node.key.Equals(key)) @@ -195,7 +194,7 @@ public bool Contains(object key) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } - for (DictionaryNode node = head; node != null; node = node.next) + for (DictionaryNode? node = head; node != null; node = node.next) { if (node.key.Equals(key)) { @@ -219,7 +218,7 @@ public void CopyTo(Array array, int index) if (array.Length - index < this.Count) throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index)); - for (DictionaryNode node = head; node != null; node = node.next) + for (DictionaryNode? node = head; node != null; node = node.next) { array.SetValue(new DictionaryEntry(node.key, node.value), index); index++; @@ -243,8 +242,8 @@ public void Remove(object key) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } version++; - DictionaryNode last = null; - DictionaryNode node; + DictionaryNode? last = null; + DictionaryNode? node; for (node = head; node != null; node = node.next) { if (node.key.Equals(key)) @@ -263,7 +262,7 @@ public void Remove(object key) } else { - last.next = node.next; + last!.next = node.next; } count--; } @@ -271,7 +270,7 @@ public void Remove(object key) private class NodeEnumerator : IDictionaryEnumerator { private ListDictionaryInternal list; - private DictionaryNode current; + private DictionaryNode? current; private int version; private bool start; @@ -284,7 +283,9 @@ public NodeEnumerator(ListDictionaryInternal list) current = null; } +#pragma warning disable CS8612 // TODO-NULLABLE: Covariant parameter types (https://github.com/dotnet/roslyn/issues/30958) public object Current +#pragma warning restore CS8612 { get { @@ -316,7 +317,7 @@ public object Key } } - public object Value + public object? Value { get { @@ -382,7 +383,7 @@ void ICollection.CopyTo(Array array, int index) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < list.Count) throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index)); - for (DictionaryNode node = list.head; node != null; node = node.next) + for (DictionaryNode? node = list.head; node != null; node = node.next) { array.SetValue(isKeys ? node.key : node.value, index); index++; @@ -394,7 +395,7 @@ int ICollection.Count get { int count = 0; - for (DictionaryNode node = list.head; node != null; node = node.next) + for (DictionaryNode? node = list.head; node != null; node = node.next) { count++; } @@ -427,7 +428,7 @@ IEnumerator IEnumerable.GetEnumerator() private class NodeKeyValueEnumerator : IEnumerator { private ListDictionaryInternal list; - private DictionaryNode current; + private DictionaryNode? current; private int version; private bool isKeys; private bool start; @@ -441,7 +442,7 @@ public NodeKeyValueEnumerator(ListDictionaryInternal list, bool isKeys) current = null; } - public object Current + public object? Current { get { @@ -489,9 +490,9 @@ public void Reset() [Serializable] private class DictionaryNode { - public object key; - public object value; - public DictionaryNode next; + public object key = null!; + public object? value; + public DictionaryNode? next; } } } diff --git a/src/Common/src/CoreLib/System/Collections/ObjectModel/Collection.cs b/src/Common/src/CoreLib/System/Collections/ObjectModel/Collection.cs index 4898c0cae20a..6cf843809e5c 100644 --- a/src/Common/src/CoreLib/System/Collections/ObjectModel/Collection.cs +++ b/src/Common/src/CoreLib/System/Collections/ObjectModel/Collection.cs @@ -26,7 +26,7 @@ public Collection(IList list) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list); } - items = list; + items = list!; // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public int Count @@ -133,7 +133,7 @@ public void InsertRange(int index, IEnumerable collection) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } - InsertItemsRange(index, collection); + InsertItemsRange(index, collection!); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public bool Remove(T item) @@ -201,7 +201,7 @@ public void ReplaceRange(int index, int count, IEnumerable collection) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } - ReplaceItemsRange(index, count, collection); + ReplaceItemsRange(index, count, collection!); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public void RemoveAt(int index) @@ -308,7 +308,7 @@ void ICollection.CopyTo(Array array, int index) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (array.Rank != 1) + if (array!.Rank != 1) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } @@ -340,7 +340,7 @@ void ICollection.CopyTo(Array array, int index) // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // - Type targetType = array.GetType().GetElementType(); + Type targetType = array.GetType().GetElementType()!; Type sourceType = typeof(T); if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { @@ -351,7 +351,7 @@ void ICollection.CopyTo(Array array, int index) // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // - object[] objects = array as object[]; + object?[]? objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); @@ -362,7 +362,7 @@ void ICollection.CopyTo(Array array, int index) { for (int i = 0; i < count; i++) { - objects[index++] = items[i]; + objects![index++] = items[i]; // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } } catch (ArrayTypeMismatchException) @@ -372,7 +372,7 @@ void ICollection.CopyTo(Array array, int index) } } - object IList.this[int index] + object? IList.this[int index] { get { return items[index]; } set @@ -381,7 +381,7 @@ object IList.this[int index] try { - this[index] = (T)value; + this[index] = (T)value!; } catch (InvalidCastException) { @@ -414,7 +414,7 @@ bool IList.IsFixedSize } } - int IList.Add(object value) + int IList.Add(object? value) { if (items.IsReadOnly) { @@ -424,7 +424,7 @@ int IList.Add(object value) try { - Add((T)value); + Add((T)value!); } catch (InvalidCastException) { @@ -434,25 +434,25 @@ int IList.Add(object value) return this.Count - 1; } - bool IList.Contains(object value) + bool IList.Contains(object? value) { if (IsCompatibleObject(value)) { - return Contains((T)value); + return Contains((T)value!); } return false; } - int IList.IndexOf(object value) + int IList.IndexOf(object? value) { if (IsCompatibleObject(value)) { - return IndexOf((T)value); + return IndexOf((T)value!); } return -1; } - void IList.Insert(int index, object value) + void IList.Insert(int index, object? value) { if (items.IsReadOnly) { @@ -462,7 +462,7 @@ void IList.Insert(int index, object value) try { - Insert(index, (T)value); + Insert(index, (T)value!); } catch (InvalidCastException) { @@ -470,7 +470,7 @@ void IList.Insert(int index, object value) } } - void IList.Remove(object value) + void IList.Remove(object? value) { if (items.IsReadOnly) { @@ -479,15 +479,15 @@ void IList.Remove(object value) if (IsCompatibleObject(value)) { - Remove((T)value); + Remove((T)value!); } } - private static bool IsCompatibleObject(object value) + private static bool IsCompatibleObject(object? value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable. // Note that default(T) is not equal to null for value types except when T is Nullable. - return ((value is T) || (value == null && default(T) == null)); + return ((value is T) || (value == null && default(T)! == null)); } } } diff --git a/src/Common/src/CoreLib/System/Collections/ObjectModel/ReadOnlyCollection.cs b/src/Common/src/CoreLib/System/Collections/ObjectModel/ReadOnlyCollection.cs index 9d463da751dc..69b342416943 100644 --- a/src/Common/src/CoreLib/System/Collections/ObjectModel/ReadOnlyCollection.cs +++ b/src/Common/src/CoreLib/System/Collections/ObjectModel/ReadOnlyCollection.cs @@ -21,7 +21,7 @@ public ReadOnlyCollection(IList list) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list); } - this.list = list; + this.list = list!; // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public int Count @@ -127,7 +127,7 @@ void ICollection.CopyTo(Array array, int index) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (array.Rank != 1) + if (array!.Rank != 1) // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } @@ -159,7 +159,7 @@ void ICollection.CopyTo(Array array, int index) // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // - Type targetType = array.GetType().GetElementType(); + Type targetType = array.GetType().GetElementType()!; Type sourceType = typeof(T); if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { @@ -170,7 +170,7 @@ void ICollection.CopyTo(Array array, int index) // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // - object[] objects = array as object[]; + object?[]? objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); @@ -181,7 +181,7 @@ void ICollection.CopyTo(Array array, int index) { for (int i = 0; i < count; i++) { - objects[index++] = list[i]; + objects![index++] = list[i]; // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } } catch (ArrayTypeMismatchException) @@ -201,7 +201,7 @@ bool IList.IsReadOnly get { return true; } } - object IList.this[int index] + object? IList.this[int index] { get { return list[index]; } set @@ -210,7 +210,7 @@ object IList.this[int index] } } - int IList.Add(object value) + int IList.Add(object? value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); return -1; @@ -221,37 +221,37 @@ void IList.Clear() ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } - private static bool IsCompatibleObject(object value) + private static bool IsCompatibleObject(object? value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable. // Note that default(T) is not equal to null for value types except when T is Nullable. - return ((value is T) || (value == null && default(T) == null)); + return ((value is T) || (value == null && default(T)! == null)); } - bool IList.Contains(object value) + bool IList.Contains(object? value) { if (IsCompatibleObject(value)) { - return Contains((T)value); + return Contains((T)value!); } return false; } - int IList.IndexOf(object value) + int IList.IndexOf(object? value) { if (IsCompatibleObject(value)) { - return IndexOf((T)value); + return IndexOf((T)value!); } return -1; } - void IList.Insert(int index, object value) + void IList.Insert(int index, object? value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } - void IList.Remove(object value) + void IList.Remove(object? value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } diff --git a/src/Common/src/CoreLib/System/ComponentModel/DefaultValueAttribute.cs b/src/Common/src/CoreLib/System/ComponentModel/DefaultValueAttribute.cs index 9380064337d9..97aceddb70f0 100644 --- a/src/Common/src/CoreLib/System/ComponentModel/DefaultValueAttribute.cs +++ b/src/Common/src/CoreLib/System/ComponentModel/DefaultValueAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; @@ -68,7 +67,7 @@ bool TryConvertFromInvariantString(Type? typeToConvert, string? stringValue, out // lazy init reflection objects if (s_convertFromInvariantString == null) { - Type typeDescriptorType = Type.GetType("System.ComponentModel.TypeDescriptor, System.ComponentModel.TypeConverter", throwOnError: false); + Type? typeDescriptorType = Type.GetType("System.ComponentModel.TypeDescriptor, System.ComponentModel.TypeConverter", throwOnError: false); MethodInfo? mi = typeDescriptorType?.GetMethod("ConvertFromInvariantString", BindingFlags.NonPublic | BindingFlags.Static); Volatile.Write(ref s_convertFromInvariantString, mi == null ? new object() : mi.CreateDelegate(typeof(Func))); } diff --git a/src/Common/src/CoreLib/System/ComponentModel/EditorBrowsableAttribute.cs b/src/Common/src/CoreLib/System/ComponentModel/EditorBrowsableAttribute.cs index 5ab2693eab24..050708661c12 100644 --- a/src/Common/src/CoreLib/System/ComponentModel/EditorBrowsableAttribute.cs +++ b/src/Common/src/CoreLib/System/ComponentModel/EditorBrowsableAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.ComponentModel { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Interface)] diff --git a/src/Common/src/CoreLib/System/ComponentModel/EditorBrowsableState.cs b/src/Common/src/CoreLib/System/ComponentModel/EditorBrowsableState.cs index bb935e83c5e8..a98669c4e963 100644 --- a/src/Common/src/CoreLib/System/ComponentModel/EditorBrowsableState.cs +++ b/src/Common/src/CoreLib/System/ComponentModel/EditorBrowsableState.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.ComponentModel { public enum EditorBrowsableState diff --git a/src/Common/src/CoreLib/System/Convert.Base64.cs b/src/Common/src/CoreLib/System/Convert.Base64.cs index aef0cdeca3fc..332f3b9d8b16 100644 --- a/src/Common/src/CoreLib/System/Convert.Base64.cs +++ b/src/Common/src/CoreLib/System/Convert.Base64.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/Convert.cs b/src/Common/src/CoreLib/System/Convert.cs index 03b1bccede4b..412528ce2617 100644 --- a/src/Common/src/CoreLib/System/Convert.cs +++ b/src/Common/src/CoreLib/System/Convert.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Globalization; using System.Threading; @@ -12,6 +11,7 @@ using System.Runtime.Versioning; using System.Security; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System { @@ -312,7 +312,8 @@ internal static object DefaultToType(IConvertible value, Type targetType, IForma return ChangeType(value, conversionType, CultureInfo.CurrentCulture); } - public static object? ChangeType(object? value, Type conversionType, IFormatProvider? provider) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + [return: NotNullIfNotNull("value")] + public static object? ChangeType(object? value, Type conversionType, IFormatProvider? provider) { if (conversionType is null) { @@ -373,22 +374,31 @@ internal static object DefaultToType(IConvertible value, Type targetType, IForma return ic.ToType(conversionType, provider); } + [DoesNotReturn] private static void ThrowCharOverflowException() { throw new OverflowException(SR.Overflow_Char); } + [DoesNotReturn] private static void ThrowByteOverflowException() { throw new OverflowException(SR.Overflow_Byte); } + [DoesNotReturn] private static void ThrowSByteOverflowException() { throw new OverflowException(SR.Overflow_SByte); } + [DoesNotReturn] private static void ThrowInt16OverflowException() { throw new OverflowException(SR.Overflow_Int16); } + [DoesNotReturn] private static void ThrowUInt16OverflowException() { throw new OverflowException(SR.Overflow_UInt16); } + [DoesNotReturn] private static void ThrowInt32OverflowException() { throw new OverflowException(SR.Overflow_Int32); } + [DoesNotReturn] private static void ThrowUInt32OverflowException() { throw new OverflowException(SR.Overflow_UInt32); } + [DoesNotReturn] private static void ThrowInt64OverflowException() { throw new OverflowException(SR.Overflow_Int64); } + [DoesNotReturn] private static void ThrowUInt64OverflowException() { throw new OverflowException(SR.Overflow_UInt64); } // Conversions to Boolean @@ -2154,14 +2164,16 @@ public static string ToString(DateTime value, IFormatProvider? provider) return value.ToString(provider); } - public static string? ToString(string? value) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + [return: NotNullIfNotNull("value")] + public static string? ToString(string? value) { return value; } - public static string? ToString(string? value, IFormatProvider? provider) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + [return: NotNullIfNotNull("value")] + public static string? ToString(string? value, IFormatProvider? provider) { - return value; // avoid the null check + return value; } diff --git a/src/Common/src/CoreLib/System/CoreLib.cs b/src/Common/src/CoreLib/System/CoreLib.cs index 9e18412742cf..9c5d1c1aa377 100644 --- a/src/Common/src/CoreLib/System/CoreLib.cs +++ b/src/Common/src/CoreLib/System/CoreLib.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { // This class is used to define the name of the base class library diff --git a/src/Common/src/CoreLib/System/CurrentSystemTimeZone.cs b/src/Common/src/CoreLib/System/CurrentSystemTimeZone.cs index 5b5fdd63aa7c..6c52bf7b35b3 100644 --- a/src/Common/src/CoreLib/System/CurrentSystemTimeZone.cs +++ b/src/Common/src/CoreLib/System/CurrentSystemTimeZone.cs @@ -17,7 +17,6 @@ ** ============================================================*/ -#nullable enable using System.Collections; using System.Globalization; @@ -207,7 +206,7 @@ private DaylightTime GetCachedDaylightChanges(int year) } } - return (DaylightTime)m_CachedDaylightChanges[objYear]; + return (DaylightTime)m_CachedDaylightChanges[objYear]!; } // The per-year information is cached in this instance value. As a result it can diff --git a/src/Common/src/CoreLib/System/DBNull.cs b/src/Common/src/CoreLib/System/DBNull.cs index 5d2a12e96e02..8e9f55a7729b 100644 --- a/src/Common/src/CoreLib/System/DBNull.cs +++ b/src/Common/src/CoreLib/System/DBNull.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/DataMisalignedException.cs b/src/Common/src/CoreLib/System/DataMisalignedException.cs index 8c2618458a90..2b49e5a98575 100644 --- a/src/Common/src/CoreLib/System/DataMisalignedException.cs +++ b/src/Common/src/CoreLib/System/DataMisalignedException.cs @@ -9,7 +9,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/DateTime.Unix.cs b/src/Common/src/CoreLib/System/DateTime.Unix.cs index f5d1a8f531c8..2c4de3e1a85e 100644 --- a/src/Common/src/CoreLib/System/DateTime.Unix.cs +++ b/src/Common/src/CoreLib/System/DateTime.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { public readonly partial struct DateTime @@ -19,8 +18,8 @@ public static DateTime UtcNow } #endif - internal static DateTime FromFileTimeLeapSecondsAware(long fileTime) => default; - internal static long ToFileTimeLeapSecondsAware(long ticks) => default; + private static DateTime FromFileTimeLeapSecondsAware(long fileTime) => default; + private static long ToFileTimeLeapSecondsAware(long ticks) => default; // IsValidTimeWithLeapSeconds is not expected to be called at all for now on non-Windows platforms internal static bool IsValidTimeWithLeapSeconds(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind) => false; diff --git a/src/Common/src/CoreLib/System/DateTime.Win32.cs b/src/Common/src/CoreLib/System/DateTime.Win32.cs index d742c891c7c0..2a054375a494 100644 --- a/src/Common/src/CoreLib/System/DateTime.Win32.cs +++ b/src/Common/src/CoreLib/System/DateTime.Win32.cs @@ -2,9 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - namespace System { public readonly partial struct DateTime diff --git a/src/Common/src/CoreLib/System/DateTime.cs b/src/Common/src/CoreLib/System/DateTime.cs index deb2da287693..2317221b5a78 100644 --- a/src/Common/src/CoreLib/System/DateTime.cs +++ b/src/Common/src/CoreLib/System/DateTime.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Diagnostics; using System.Threading; diff --git a/src/Common/src/CoreLib/System/DateTimeKind.cs b/src/Common/src/CoreLib/System/DateTimeKind.cs index 1f2ce006d88c..33c9bd925fe2 100644 --- a/src/Common/src/CoreLib/System/DateTimeKind.cs +++ b/src/Common/src/CoreLib/System/DateTimeKind.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { // This enum is used to indentify DateTime instances in cases when they are known to be in local time, diff --git a/src/Common/src/CoreLib/System/DateTimeOffset.cs b/src/Common/src/CoreLib/System/DateTimeOffset.cs index 8b0ea368a67d..e328726a4075 100644 --- a/src/Common/src/CoreLib/System/DateTimeOffset.cs +++ b/src/Common/src/CoreLib/System/DateTimeOffset.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; @@ -659,7 +658,7 @@ public static DateTimeOffset Parse(string input) public static DateTimeOffset Parse(string input, IFormatProvider? formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); - return Parse(input!, formatProvider, DateTimeStyles.None); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return Parse(input!, formatProvider, DateTimeStyles.None); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } public static DateTimeOffset Parse(string input, IFormatProvider? formatProvider, DateTimeStyles styles) @@ -690,7 +689,7 @@ public static DateTimeOffset ParseExact(string input, string format, IFormatProv { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); - return ParseExact(input!, format!, formatProvider, DateTimeStyles.None); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + return ParseExact(input!, format!, formatProvider, DateTimeStyles.None); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected } // Constructs a DateTimeOffset from a string. The string must specify a diff --git a/src/Common/src/CoreLib/System/DayOfWeek.cs b/src/Common/src/CoreLib/System/DayOfWeek.cs index 19cb69a796a4..f67d10e18150 100644 --- a/src/Common/src/CoreLib/System/DayOfWeek.cs +++ b/src/Common/src/CoreLib/System/DayOfWeek.cs @@ -11,7 +11,6 @@ ** ============================================================*/ -#nullable enable namespace System { public enum DayOfWeek diff --git a/src/Common/src/CoreLib/System/Decimal.DecCalc.cs b/src/Common/src/CoreLib/System/Decimal.DecCalc.cs index 04eb9aa09b32..342aec9a8acc 100644 --- a/src/Common/src/CoreLib/System/Decimal.DecCalc.cs +++ b/src/Common/src/CoreLib/System/Decimal.DecCalc.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/Decimal.cs b/src/Common/src/CoreLib/System/Decimal.cs index 6f2a0a15c63e..72ac754776e1 100644 --- a/src/Common/src/CoreLib/System/Decimal.cs +++ b/src/Common/src/CoreLib/System/Decimal.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers.Binary; using System.Diagnostics; using System.Globalization; diff --git a/src/Common/src/CoreLib/System/DefaultBinder.cs b/src/Common/src/CoreLib/System/DefaultBinder.cs index f8d8c0c1685a..32fa9f625332 100644 --- a/src/Common/src/CoreLib/System/DefaultBinder.cs +++ b/src/Common/src/CoreLib/System/DefaultBinder.cs @@ -29,13 +29,13 @@ partial class DefaultBinder : Binder // The most specific match will be selected. // public sealed override MethodBase BindToMethod( - BindingFlags bindingAttr, MethodBase[] match, ref object[] args, - ParameterModifier[] modifiers, CultureInfo cultureInfo, string[] names, out object state) + BindingFlags bindingAttr, MethodBase[] match, ref object?[] args, + ParameterModifier[]? modifiers, CultureInfo? cultureInfo, string[]? names, out object? state) { if (match == null || match.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(match)); - MethodBase[] candidates = (MethodBase[])match.Clone(); + MethodBase?[] candidates = (MethodBase[])match.Clone(); int i; int j; @@ -52,7 +52,7 @@ public sealed override MethodBase BindToMethod( for (i = 0; i < candidates.Length; i++) { - ParameterInfo[] par = candidates[i].GetParametersNoCopy(); + ParameterInfo[] par = candidates[i]!.GetParametersNoCopy(); // args.Length + 1 takes into account the possibility of a last paramArray that can be omitted paramOrder[i] = new int[(par.Length > args.Length) ? par.Length : args.Length]; @@ -84,7 +84,7 @@ public sealed override MethodBase BindToMethod( { if (args[i] != null) { - argTypes[i] = args[i].GetType(); + argTypes[i] = args[i]!.GetType(); } } #endregion @@ -94,7 +94,7 @@ public sealed override MethodBase BindToMethod( int CurIdx = 0; bool defaultValueBinding = ((bindingAttr & BindingFlags.OptionalParamBinding) != 0); - Type paramArrayType = null; + Type? paramArrayType; #region Filter methods by parameter count and type for (i = 0; i < candidates.Length; i++) @@ -106,7 +106,7 @@ public sealed override MethodBase BindToMethod( continue; // Validate the parameters. - ParameterInfo[] par = candidates[i].GetParametersNoCopy(); + ParameterInfo[] par = candidates[i]!.GetParametersNoCopy(); // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) #region Match method by parameter count if (par.Length == 0) @@ -114,7 +114,7 @@ public sealed override MethodBase BindToMethod( #region No formal parameters if (args.Length != 0) { - if ((candidates[i].CallingConvention & CallingConventions.VarArgs) == 0) + if ((candidates[i]!.CallingConvention & CallingConventions.VarArgs) == 0) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) continue; } @@ -185,7 +185,7 @@ public sealed override MethodBase BindToMethod( } #endregion - Type pCls = null; + Type pCls; int argsToCheck = (paramArrayType != null) ? par.Length - 1 : args.Length; #region Match method by parameter type @@ -196,7 +196,7 @@ public sealed override MethodBase BindToMethod( pCls = par[j].ParameterType; if (pCls.IsByRef) - pCls = pCls.GetElementType(); + pCls = pCls.GetElementType()!; // the type is the same if (pCls == argTypes[paramOrder[i][j]]) @@ -217,7 +217,7 @@ public sealed override MethodBase BindToMethod( // now do a "classic" type check if (pCls.IsPrimitive) { - if (argTypes[paramOrder[i][j]] == null || !CanChangePrimitiveObjectToType(args[paramOrder[i][j]], pCls)) + if (argTypes[paramOrder[i][j]] == null || !CanChangePrimitive(args[paramOrder[i][j]]!.GetType(), pCls)) //TODO-NULLABLE https://github.com/dotnet/csharplang/issues/2388 { break; } @@ -247,7 +247,7 @@ public sealed override MethodBase BindToMethod( { if (paramArrayType.IsPrimitive) { - if (argTypes[j] == null || !CanChangePrimitiveObjectToType(args[j], paramArrayType)) + if (argTypes[j] == null || !CanChangePrimitive(args[j]?.GetType(), paramArrayType)) //TODO-NULLABLE https://github.com/dotnet/csharplang/issues/2388 break; } else @@ -275,7 +275,7 @@ public sealed override MethodBase BindToMethod( { #region This is a valid routine so we move it up the candidates list paramOrder[CurIdx] = paramOrder[i]; - paramArrayTypes[CurIdx] = paramArrayType; + paramArrayTypes[CurIdx] = paramArrayType!; candidates[CurIdx++] = candidates[i]; #endregion } @@ -297,7 +297,7 @@ public sealed override MethodBase BindToMethod( // If the parameters and the args are not the same length or there is a paramArray // then we need to create a argument array. - ParameterInfo[] parms = candidates[0].GetParametersNoCopy(); + ParameterInfo[] parms = candidates[0]!.GetParametersNoCopy(); if (parms.Length == args.Length) { @@ -313,7 +313,7 @@ public sealed override MethodBase BindToMethod( } else if (parms.Length > args.Length) { - object[] objs = new object[parms.Length]; + object?[] objs = new object[parms.Length]; for (i = 0; i < args.Length; i++) objs[i] = args[i]; @@ -331,7 +331,7 @@ public sealed override MethodBase BindToMethod( } else { - if ((candidates[0].CallingConvention & CallingConventions.VarArgs) == 0) + if ((candidates[0]!.CallingConvention & CallingConventions.VarArgs) == 0) { object[] objs = new object[parms.Length]; int paramArrayPos = parms.Length - 1; @@ -343,7 +343,7 @@ public sealed override MethodBase BindToMethod( } #endregion - return candidates[0]; + return candidates[0]!; } int currentMin = 0; @@ -351,8 +351,8 @@ public sealed override MethodBase BindToMethod( for (i = 1; i < CurIdx; i++) { #region Walk all of the methods looking the most specific method to invoke - int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder[currentMin], paramArrayTypes[currentMin], - candidates[i], paramOrder[i], paramArrayTypes[i], argTypes, args); + int newMin = FindMostSpecificMethod(candidates[currentMin]!, paramOrder[currentMin], paramArrayTypes[currentMin], + candidates[i]!, paramOrder[i], paramArrayTypes[i], argTypes, args); if (newMin == 0) { @@ -378,7 +378,7 @@ public sealed override MethodBase BindToMethod( // If the parameters and the args are not the same length or there is a paramArray // then we need to create a argument array. - ParameterInfo[] parameters = candidates[currentMin].GetParametersNoCopy(); + ParameterInfo[] parameters = candidates[currentMin]!.GetParametersNoCopy(); if (parameters.Length == args.Length) { if (paramArrayTypes[currentMin] != null) @@ -393,7 +393,7 @@ public sealed override MethodBase BindToMethod( } else if (parameters.Length > args.Length) { - object[] objs = new object[parameters.Length]; + object?[] objs = new object[parameters.Length]; for (i = 0; i < args.Length; i++) objs[i] = args[i]; @@ -414,7 +414,7 @@ public sealed override MethodBase BindToMethod( } else { - if ((candidates[currentMin].CallingConvention & CallingConventions.VarArgs) == 0) + if ((candidates[currentMin]!.CallingConvention & CallingConventions.VarArgs) == 0) { object[] objs = new object[parameters.Length]; int paramArrayPos = parameters.Length - 1; @@ -425,13 +425,13 @@ public sealed override MethodBase BindToMethod( } } - return candidates[currentMin]; + return candidates[currentMin]!; } // Given a set of fields that match the base criteria, select a field. // if value is null then we have no way to select a field - public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo cultureInfo) + public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo? cultureInfo) { if (match == null) { @@ -442,7 +442,7 @@ public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo // Find the method that match... int CurIdx = 0; - Type valueType = null; + Type valueType; FieldInfo[] candidates = (FieldInfo[])match.Clone(); @@ -475,7 +475,7 @@ public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo } if (pCls.IsPrimitive) { - if (CanChangePrimitiveObjectToType(value, pCls)) + if (CanChangePrimitive(valueType, pCls)) { candidates[CurIdx++] = candidates[i]; continue; @@ -521,7 +521,7 @@ public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo // Given a set of methods that match the base criteria, select a method based // upon an array of types. This method should return null if no method matchs // the criteria. - public sealed override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers) + public sealed override MethodBase? SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[]? modifiers) { int i; int j; @@ -557,7 +557,7 @@ public sealed override MethodBase SelectMethod(BindingFlags bindingAttr, MethodB if (pCls == typeof(object)) continue; - Type type = types[j]; + Type? type = types[j]; if (type is SignatureType signatureType) { if (!(candidates[i] is MethodInfo methodInfo)) @@ -614,8 +614,8 @@ public sealed override MethodBase SelectMethod(BindingFlags bindingAttr, MethodB } // Given a set of properties that match the base criteria, select one. - public sealed override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, - Type[] indexes, ParameterModifier[] modifiers) + public sealed override PropertyInfo? SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type? returnType, + Type[]? indexes, ParameterModifier[]? modifiers) { // Allow a null indexes array. But if it is not null, every element must be non-null as well. if (indexes != null) @@ -732,7 +732,7 @@ public sealed override PropertyInfo SelectProperty(BindingFlags bindingAttr, Pro // ChangeType // The default binder doesn't support any change type functionality. // This is because the default is built into the low level invoke code. - public override object ChangeType(object value, Type type, CultureInfo cultureInfo) + public override object ChangeType(object value, Type type, CultureInfo? cultureInfo) { throw new NotSupportedException(SR.NotSupported_ChangeType); } @@ -771,7 +771,7 @@ public sealed override void ReorderArgumentArray(ref object[] args, object state // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) - public static MethodBase ExactBinding(MethodBase[] match, Type[] types, ParameterModifier[] modifiers) + public static MethodBase? ExactBinding(MethodBase[] match, Type[] types, ParameterModifier[]? modifiers) { if (match == null) throw new ArgumentNullException(nameof(match)); @@ -814,12 +814,12 @@ public static MethodBase ExactBinding(MethodBase[] match, Type[] types, Paramete // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) - public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match, Type returnType, Type[] types, ParameterModifier[] modifiers) + public static PropertyInfo? ExactPropertyBinding(PropertyInfo[] match, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { if (match == null) throw new ArgumentNullException(nameof(match)); - PropertyInfo bestMatch = null; + PropertyInfo? bestMatch = null; int typesLength = (types != null) ? types.Length : 0; for (int i = 0; i < match.Length; i++) { @@ -830,7 +830,7 @@ public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match, Type retur Type pCls = par[j].ParameterType; // If the classes exactly match continue - if (pCls != types[j]) + if (pCls != types![j]) break; } if (j < typesLength) @@ -846,9 +846,9 @@ public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match, Type retur return bestMatch; } - private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type paramArrayType1, - ParameterInfo[] p2, int[] paramOrder2, Type paramArrayType2, - Type[] types, object[] args) + private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type? paramArrayType1, + ParameterInfo[] p2, int[] paramOrder2, Type? paramArrayType2, + Type[] types, object?[]? args) { // A method using params is always less specific than one not using params if (paramArrayType1 != null && paramArrayType2 == null) return 2; @@ -923,7 +923,7 @@ private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type } } - private static int FindMostSpecificType(Type c1, Type c2, Type t) + private static int FindMostSpecificType(Type c1, Type c2, Type? t) { // If the two types are exact move on... if (c1 == c2) @@ -953,22 +953,22 @@ private static int FindMostSpecificType(Type c1, Type c2, Type t) { if (c1.IsByRef && c2.IsByRef) { - c1 = c1.GetElementType(); - c2 = c2.GetElementType(); + c1 = c1.GetElementType()!; + c2 = c2.GetElementType()!; } else if (c1.IsByRef) { if (c1.GetElementType() == c2) return 2; - c1 = c1.GetElementType(); + c1 = c1.GetElementType()!; } - else + else // if (c2.IsByRef) { if (c2.GetElementType() == c1) return 1; - c2 = c2.GetElementType(); + c2 = c2.GetElementType()!; } } @@ -997,9 +997,9 @@ private static int FindMostSpecificType(Type c1, Type c2, Type t) } } - private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type paramArrayType1, - MethodBase m2, int[] paramOrder2, Type paramArrayType2, - Type[] types, object[] args) + private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type? paramArrayType1, + MethodBase m2, int[] paramOrder2, Type? paramArrayType2, + Type[] types, object?[]? args) { // Find the most specific method based on the parameters. int res = FindMostSpecific(m1.GetParametersNoCopy(), paramOrder1, paramArrayType1, @@ -1013,8 +1013,8 @@ private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type if (CompareMethodSig(m1, m2)) { // Determine the depth of the declaring types for both methods. - int hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType); - int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType); + int hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType!); + int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType!); // The most derived method is the most specific one. if (hierarchyDepth1 == hierarchyDepth2) @@ -1040,8 +1040,8 @@ private static int FindMostSpecificField(FieldInfo cur1, FieldInfo cur2) // Check to see if the fields have the same name. if (cur1.Name == cur2.Name) { - int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType); - int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType); + int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType!); + int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType!); if (hierarchyDepth1 == hierarchyDepth2) { @@ -1063,8 +1063,8 @@ private static int FindMostSpecificProperty(PropertyInfo cur1, PropertyInfo cur2 // Check to see if the fields have the same name. if (cur1.Name == cur2.Name) { - int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType); - int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType); + int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType!); + int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType!); if (hierarchyDepth1 == hierarchyDepth2) { @@ -1102,7 +1102,7 @@ private static int GetHierarchyDepth(Type t) { int depth = 0; - Type currentType = t; + Type? currentType = t; do { depth++; @@ -1112,16 +1112,16 @@ private static int GetHierarchyDepth(Type t) return depth; } - internal static MethodBase FindMostDerivedNewSlotMeth(MethodBase[] match, int cMatches) + internal static MethodBase? FindMostDerivedNewSlotMeth(MethodBase[] match, int cMatches) { int deepestHierarchy = 0; - MethodBase methWithDeepestHierarchy = null; + MethodBase? methWithDeepestHierarchy = null; for (int i = 0; i < cMatches; i++) { // Calculate the depth of the hierarchy of the declaring type of the // current method. - int currentHierarchyDepth = GetHierarchyDepth(match[i].DeclaringType); + int currentHierarchyDepth = GetHierarchyDepth(match[i].DeclaringType!); // The two methods have the same name, signature, and hierarchy depth. // This can only happen if at least one is vararg or generic. @@ -1143,9 +1143,9 @@ internal static MethodBase FindMostDerivedNewSlotMeth(MethodBase[] match, int cM // This method will sort the vars array into the mapping order stored // in the paramOrder array. - private static void ReorderParams(int[] paramOrder, object[] vars) + private static void ReorderParams(int[] paramOrder, object?[] vars) { - object[] varsCopy = new object[vars.Length]; + object?[] varsCopy = new object[vars.Length]; for (int i = 0; i < vars.Length; i++) varsCopy[i] = vars[i]; @@ -1204,6 +1204,62 @@ private static bool CreateParamOrder(int[] paramOrder, ParameterInfo[] pars, str return true; } + // CanChangePrimitive + // This will determine if the source can be converted to the target type + internal static bool CanChangePrimitive(Type? source, Type? target) + { + if ((source == typeof(IntPtr) && target == typeof(IntPtr)) || + (source == typeof(UIntPtr) && target == typeof(UIntPtr))) + return true; + + Primitives widerCodes = s_primitiveConversions[(int)(Type.GetTypeCode(source))]; + Primitives targetCode = (Primitives)(1 << (int)(Type.GetTypeCode(target))); + + return (widerCodes & targetCode) != 0; + } + + private static readonly Primitives[] s_primitiveConversions = { + /* Empty */ 0, // not primitive + /* Object */ 0, // not primitive + /* DBNull */ 0, // not primitive + /* Boolean */ Primitives.Boolean, + /* Char */ Primitives.Char | Primitives.UInt16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, + /* SByte */ Primitives.SByte | Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, + /* Byte */ Primitives.Byte | Primitives.Char | Primitives.UInt16 | Primitives.Int16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, + /* Int16 */ Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, + /* UInt16 */ Primitives.UInt16 | Primitives.UInt32 | Primitives.Int32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, + /* Int32 */ Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, + /* UInt32 */ Primitives.UInt32 | Primitives.UInt64 | Primitives.Int64 | Primitives.Single | Primitives.Double, + /* Int64 */ Primitives.Int64 | Primitives.Single | Primitives.Double, + /* UInt64 */ Primitives.UInt64 | Primitives.Single | Primitives.Double, + /* Single */ Primitives.Single | Primitives.Double, + /* Double */ Primitives.Double, + /* Decimal */ Primitives.Decimal, + /* DateTime */ Primitives.DateTime, + /* [Unused] */ 0, + /* String */ Primitives.String, + }; + + [Flags] + private enum Primitives + { + Boolean = 1 << TypeCode.Boolean, + Char = 1 << TypeCode.Char, + SByte = 1 << TypeCode.SByte, + Byte = 1 << TypeCode.Byte, + Int16 = 1 << TypeCode.Int16, + UInt16 = 1 << TypeCode.UInt16, + Int32 = 1 << TypeCode.Int32, + UInt32 = 1 << TypeCode.UInt32, + Int64 = 1 << TypeCode.Int64, + UInt64 = 1 << TypeCode.UInt64, + Single = 1 << TypeCode.Single, + Double = 1 << TypeCode.Double, + Decimal = 1 << TypeCode.Decimal, + DateTime = 1 << TypeCode.DateTime, + String = 1 << TypeCode.String, + } + internal class BinderState { internal readonly int[] _argsMap; diff --git a/src/Common/src/CoreLib/System/Delegate.cs b/src/Common/src/CoreLib/System/Delegate.cs index 79c12c137374..62c3910f9b03 100644 --- a/src/Common/src/CoreLib/System/Delegate.cs +++ b/src/Common/src/CoreLib/System/Delegate.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable +using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; @@ -13,7 +13,9 @@ public abstract partial class Delegate : ICloneable, ISerializable { public virtual object Clone() => MemberwiseClone(); - public static Delegate? Combine(Delegate? a, Delegate? b) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + [return: NotNullIfNotNull("a")] + [return: NotNullIfNotNull("b")] + public static Delegate? Combine(Delegate? a, Delegate? b) { if (a is null) return b; @@ -21,7 +23,7 @@ public abstract partial class Delegate : ICloneable, ISerializable return a.CombineImpl(b); } - public static Delegate? Combine(params Delegate?[]? delegates) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + public static Delegate? Combine(params Delegate?[]? delegates) { if (delegates == null || delegates.Length == 0) return null; diff --git a/src/Common/src/CoreLib/System/Diagnostics/CodeAnalysis/NullableAttributes.cs b/src/Common/src/CoreLib/System/Diagnostics/CodeAnalysis/NullableAttributes.cs new file mode 100644 index 000000000000..3770a5ff0ba2 --- /dev/null +++ b/src/Common/src/CoreLib/System/Diagnostics/CodeAnalysis/NullableAttributes.cs @@ -0,0 +1,128 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Diagnostics.CodeAnalysis +{ + /// Specifies that null is allowed as an input even if the corresponding type disallows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)] +#if INTERNAL_NULLABLE_ATTRIBUTES + internal +#else + public +#endif + sealed class AllowNullAttribute : Attribute { } + + /// Specifies that null is disallowed as an input even if the corresponding type allows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)] +#if INTERNAL_NULLABLE_ATTRIBUTES + internal +#else + public +#endif + sealed class DisallowNullAttribute : Attribute { } + + /// Specifies that an output may be null even if the corresponding type disallows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] +#if INTERNAL_NULLABLE_ATTRIBUTES + internal +#else + public +#endif + sealed class MaybeNullAttribute : Attribute { } + + /// Specifies that an output will not be null even if the corresponding type allows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] +#if INTERNAL_NULLABLE_ATTRIBUTES + internal +#else + public +#endif + sealed class NotNullAttribute : Attribute { } + + /// Specifies that when a method returns , the parameter may be null even if the corresponding type disallows it. + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +#if INTERNAL_NULLABLE_ATTRIBUTES + internal +#else + public +#endif + sealed class MaybeNullWhenAttribute : Attribute + { + /// Initializes the attribute with the specified return value condition. + /// + /// The return value condition. If the method returns this value, the associated parameter may be null. + /// + public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; + + /// Gets the return value condition. + public bool ReturnValue { get; } + } + + /// Specifies that when a method returns , the parameter will not be null even if the corresponding type allows it. + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +#if INTERNAL_NULLABLE_ATTRIBUTES + internal +#else + public +#endif + sealed class NotNullWhenAttribute : Attribute + { + /// Initializes the attribute with the specified return value condition. + /// + /// The return value condition. If the method returns this value, the associated parameter will not be null. + /// + public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; + + /// Gets the return value condition. + public bool ReturnValue { get; } + } + + /// Specifies that the output will be non-null if the named parameter is non-null. + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] +#if INTERNAL_NULLABLE_ATTRIBUTES + internal +#else + public +#endif + sealed class NotNullIfNotNullAttribute : Attribute + { + /// Initializes the attribute with the associated parameter name. + /// + /// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null. + /// + public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName; + + /// Gets the associated parameter name. + public string ParameterName { get; } + } + + /// Applied to a method that will never return under any circumstance. + [AttributeUsage(AttributeTargets.Method, Inherited = false)] +#if INTERNAL_NULLABLE_ATTRIBUTES + internal +#else + public +#endif + sealed class DoesNotReturnAttribute : Attribute { } + + /// Specifies that the method will not return if the associated Boolean parameter is passed the specified value. + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +#if INTERNAL_NULLABLE_ATTRIBUTES + internal +#else + public +#endif + sealed class DoesNotReturnIfAttribute : Attribute + { + /// Initializes the attribute with the specified parameter value. + /// + /// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to + /// the associated parameter matches this value. + /// + public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue; + + /// Gets the condition parameter value. + public bool ParameterValue { get; } + } +} diff --git a/src/Common/src/CoreLib/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs b/src/Common/src/CoreLib/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs index ae15b8ec6727..8ed44b0e659c 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ -#nullable enable namespace System.Diagnostics.CodeAnalysis { [AttributeUsage( @@ -24,14 +23,14 @@ namespace System.Diagnostics.CodeAnalysis [Conditional("CODE_ANALYSIS")] public sealed class SuppressMessageAttribute : Attribute { - public SuppressMessageAttribute(string? category, string? checkId) + public SuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } - public string? Category { get; } - public string? CheckId { get; } + public string Category { get; } + public string CheckId { get; } public string? Scope { get; set; } public string? Target { get; set; } public string? MessageId { get; set; } diff --git a/src/Common/src/CoreLib/System/Diagnostics/ConditionalAttribute.cs b/src/Common/src/CoreLib/System/Diagnostics/ConditionalAttribute.cs index 9af1e2b80db9..416625b779d7 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/ConditionalAttribute.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/ConditionalAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Diagnostics { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)] diff --git a/src/Common/src/CoreLib/System/Diagnostics/Contracts/ContractException.cs b/src/Common/src/CoreLib/System/Diagnostics/Contracts/ContractException.cs index 9feaa2381275..96d6eccd9c38 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Contracts/ContractException.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Contracts/ContractException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System.Diagnostics.Contracts diff --git a/src/Common/src/CoreLib/System/Diagnostics/Contracts/ContractFailedEventArgs.cs b/src/Common/src/CoreLib/System/Diagnostics/Contracts/ContractFailedEventArgs.cs index ad19e849be5a..3c58ca10da5b 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Contracts/ContractFailedEventArgs.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Contracts/ContractFailedEventArgs.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/Common/src/CoreLib/System/Diagnostics/Contracts/Contracts.cs b/src/Common/src/CoreLib/System/Diagnostics/Contracts/Contracts.cs index b9e49583f9b8..af6c1a333fb9 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Contracts/Contracts.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Contracts/Contracts.cs @@ -18,6 +18,7 @@ #define DEBUG // The behavior of this contract library should be consistent regardless of build type. using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace System.Diagnostics.Contracts @@ -180,7 +181,7 @@ public sealed class ContractOptionAttribute : Attribute private string _category; private string _setting; private bool _enabled; - private string _value; + private string? _value; public ContractOptionAttribute(string category, string setting, bool enabled) { @@ -211,7 +212,7 @@ public bool Enabled get { return _enabled; } } - public string Value + public string? Value { get { return _value; } } @@ -245,7 +246,7 @@ public static partial class Contract [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] - public static void Assume(bool condition) + public static void Assume([DoesNotReturnIf(false)] bool condition) { if (!condition) { @@ -264,7 +265,7 @@ public static void Assume(bool condition) [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] - public static void Assume(bool condition, string userMessage) + public static void Assume([DoesNotReturnIf(false)] bool condition, string? userMessage) { if (!condition) { @@ -283,7 +284,7 @@ public static void Assume(bool condition, string userMessage) [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] - public static void Assert(bool condition) + public static void Assert([DoesNotReturnIf(false)] bool condition) { if (!condition) ReportFailure(ContractFailureKind.Assert, null, null, null); @@ -297,7 +298,7 @@ public static void Assert(bool condition) [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] - public static void Assert(bool condition, string userMessage) + public static void Assert([DoesNotReturnIf(false)] bool condition, string? userMessage) { if (!condition) ReportFailure(ContractFailureKind.Assert, userMessage, null, null); @@ -335,7 +336,7 @@ public static void Requires(bool condition) /// [Pure] [Conditional("CONTRACTS_FULL")] - public static void Requires(bool condition, string userMessage) + public static void Requires(bool condition, string? userMessage) { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } @@ -366,7 +367,7 @@ public static void Requires(bool condition) where TException : Excep /// Use this form when you want to throw a particular exception. /// [Pure] - public static void Requires(bool condition, string userMessage) where TException : Exception + public static void Requires(bool condition, string? userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } @@ -403,7 +404,7 @@ public static void Ensures(bool condition) /// [Pure] [Conditional("CONTRACTS_FULL")] - public static void Ensures(bool condition, string userMessage) + public static void Ensures(bool condition, string? userMessage) { AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures"); } @@ -438,7 +439,7 @@ public static void EnsuresOnThrow(bool condition) where TException : /// [Pure] [Conditional("CONTRACTS_FULL")] - public static void EnsuresOnThrow(bool condition, string userMessage) where TException : Exception + public static void EnsuresOnThrow(bool condition, string? userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow"); } @@ -454,7 +455,7 @@ public static void EnsuresOnThrow(bool condition, string userMessage /// This method can only be used within the argument to the contract. /// [Pure] - public static T Result() { return default; } + public static T Result() { return default!; } /// /// Represents the final (output) value of an out parameter when returning from a method. @@ -466,7 +467,7 @@ public static void EnsuresOnThrow(bool condition, string userMessage /// This method can only be used within the argument to the contract. /// [Pure] - public static T ValueAtReturn(out T value) { value = default; return value; } + public static T ValueAtReturn(out T value) { value = default!; return value; } /// /// Represents the value of as it was at the start of the method or property. @@ -478,7 +479,7 @@ public static void EnsuresOnThrow(bool condition, string userMessage /// This method can only be used within the argument to the contract. /// [Pure] - public static T OldValue(T value) { return default; } + public static T OldValue(T value) { return default!; } #endregion Old, Result, and Out Parameters @@ -514,7 +515,7 @@ public static void Invariant(bool condition) /// [Pure] [Conditional("CONTRACTS_FULL")] - public static void Invariant(bool condition, string userMessage) + public static void Invariant(bool condition, string? userMessage) { AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant"); } @@ -651,10 +652,10 @@ private static void AssertMustUseRewriter(ContractFailureKind kind, string contr // find the first non-mscorlib assembly. Assembly thisAssembly = typeof(Contract).Assembly; // In case we refactor mscorlib, use Contract class instead of Object. StackTrace stack = new StackTrace(); - Assembly probablyNotRewritten = null; + Assembly? probablyNotRewritten = null; for (int i = 0; i < stack.FrameCount; i++) { - Assembly caller = stack.GetFrame(i).GetMethod()?.DeclaringType.Assembly; + Assembly? caller = stack.GetFrame(i)!.GetMethod()?.DeclaringType!.Assembly; if (caller != null && caller != thisAssembly) { probablyNotRewritten = caller; @@ -664,7 +665,7 @@ private static void AssertMustUseRewriter(ContractFailureKind kind, string contr if (probablyNotRewritten == null) probablyNotRewritten = thisAssembly; - string simpleName = probablyNotRewritten.GetName().Name; + string? simpleName = probablyNotRewritten.GetName().Name; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null); } @@ -679,7 +680,7 @@ private static void AssertMustUseRewriter(ContractFailureKind kind, string contr /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// [System.Diagnostics.DebuggerNonUserCode] - private static void ReportFailure(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException) + private static void ReportFailure(ContractFailureKind failureKind, string? userMessage, string? conditionText, Exception? innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); diff --git a/src/Common/src/CoreLib/System/Diagnostics/Debug.cs b/src/Common/src/CoreLib/System/Diagnostics/Debug.cs index 590588a27ed4..251ac229ea8c 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Debug.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Debug.cs @@ -2,9 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable // Do not remove this, it is needed to retain calls to these conditional methods in release builds #define DEBUG + +using System.Diagnostics.CodeAnalysis; using System.Threading; namespace System.Diagnostics @@ -86,19 +87,19 @@ public static void Print(string format, params object?[] args) } [System.Diagnostics.Conditional("DEBUG")] - public static void Assert(bool condition) + public static void Assert([DoesNotReturnIf(false)] bool condition) { Assert(condition, string.Empty, string.Empty); } [System.Diagnostics.Conditional("DEBUG")] - public static void Assert(bool condition, string? message) + public static void Assert([DoesNotReturnIf(false)] bool condition, string? message) { Assert(condition, message, string.Empty); } [System.Diagnostics.Conditional("DEBUG")] - public static void Assert(bool condition, string? message, string? detailMessage) + public static void Assert([DoesNotReturnIf(false)] bool condition, string? message, string? detailMessage) { if (!condition) { @@ -122,19 +123,21 @@ internal static void ContractFailure(string message, string detailMessage, strin } [System.Diagnostics.Conditional("DEBUG")] + [DoesNotReturn] public static void Fail(string? message) { Fail(message, string.Empty); } [System.Diagnostics.Conditional("DEBUG")] + [DoesNotReturn] public static void Fail(string? message, string? detailMessage) { s_provider.Fail(message, detailMessage); } [System.Diagnostics.Conditional("DEBUG")] - public static void Assert(bool condition, string? message, string detailMessageFormat, params object?[] args) + public static void Assert([DoesNotReturnIf(false)] bool condition, string? message, string detailMessageFormat, params object?[] args) { Assert(condition, message, string.Format(detailMessageFormat, args)); } diff --git a/src/Common/src/CoreLib/System/Diagnostics/DebugProvider.Unix.cs b/src/Common/src/CoreLib/System/Diagnostics/DebugProvider.Unix.cs index bc3e86c9fc09..0799d0929de2 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/DebugProvider.Unix.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/DebugProvider.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; namespace System.Diagnostics diff --git a/src/Common/src/CoreLib/System/Diagnostics/DebugProvider.Windows.cs b/src/Common/src/CoreLib/System/Diagnostics/DebugProvider.Windows.cs index 12ea0160a18f..e382e8130194 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/DebugProvider.Windows.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/DebugProvider.Windows.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable - namespace System.Diagnostics { public partial class DebugProvider diff --git a/src/Common/src/CoreLib/System/Diagnostics/DebugProvider.cs b/src/Common/src/CoreLib/System/Diagnostics/DebugProvider.cs index 3c762733c41c..939f37179ece 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/DebugProvider.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/DebugProvider.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable // Do not remove this, it is needed to retain calls to these conditional methods in release builds #define DEBUG @@ -98,7 +97,7 @@ private string GetIndentString() int indentCount = Debug.IndentSize * Debug.IndentLevel; if (_indentString?.Length == indentCount) { - return _indentString!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34942 + return _indentString!; // TODO-NULLABLE: Null conditional access (https://github.com/dotnet/roslyn/issues/34942) } return _indentString = new string(' ', indentCount); } diff --git a/src/Common/src/CoreLib/System/Diagnostics/DebuggableAttribute.cs b/src/Common/src/CoreLib/System/Diagnostics/DebuggableAttribute.cs index 308f6835b3e2..d05f8471b364 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/DebuggableAttribute.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/DebuggableAttribute.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable - namespace System.Diagnostics { // Attribute class used by the compiler to mark modules. diff --git a/src/Common/src/CoreLib/System/Diagnostics/DebuggerBrowsableAttribute.cs b/src/Common/src/CoreLib/System/Diagnostics/DebuggerBrowsableAttribute.cs index 4bd42caa927b..8a53052b6fca 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/DebuggerBrowsableAttribute.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/DebuggerBrowsableAttribute.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable - namespace System.Diagnostics { // DebuggerBrowsableState states are defined as follows: diff --git a/src/Common/src/CoreLib/System/Diagnostics/DebuggerDisplayAttribute.cs b/src/Common/src/CoreLib/System/Diagnostics/DebuggerDisplayAttribute.cs index 5f670852c4c7..c9738610d5d4 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/DebuggerDisplayAttribute.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/DebuggerDisplayAttribute.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable - namespace System.Diagnostics { // This attribute is used to control what is displayed for the given class or field diff --git a/src/Common/src/CoreLib/System/Diagnostics/DebuggerHiddenAttribute.cs b/src/Common/src/CoreLib/System/Diagnostics/DebuggerHiddenAttribute.cs index 4ee79302c053..ace452e911c3 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/DebuggerHiddenAttribute.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/DebuggerHiddenAttribute.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable - namespace System.Diagnostics { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Diagnostics/DebuggerNonUserCodeAttribute.cs b/src/Common/src/CoreLib/System/Diagnostics/DebuggerNonUserCodeAttribute.cs index c4e87ab8f4c2..1b61cb726285 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/DebuggerNonUserCodeAttribute.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/DebuggerNonUserCodeAttribute.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable - namespace System.Diagnostics { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor | AttributeTargets.Struct, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Diagnostics/DebuggerStepThroughAttribute.cs b/src/Common/src/CoreLib/System/Diagnostics/DebuggerStepThroughAttribute.cs index 633e38d1b9ca..82a164771e85 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/DebuggerStepThroughAttribute.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/DebuggerStepThroughAttribute.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable - namespace System.Diagnostics { #if PROJECTN diff --git a/src/Common/src/CoreLib/System/Diagnostics/DebuggerStepperBoundaryAttribute.cs b/src/Common/src/CoreLib/System/Diagnostics/DebuggerStepperBoundaryAttribute.cs index 1db7fba9a467..647f2fdb00a1 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/DebuggerStepperBoundaryAttribute.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/DebuggerStepperBoundaryAttribute.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable - namespace System.Diagnostics { /// Indicates the code following the attribute is to be executed in run, not step, mode. diff --git a/src/Common/src/CoreLib/System/Diagnostics/DebuggerTypeProxyAttribute.cs b/src/Common/src/CoreLib/System/Diagnostics/DebuggerTypeProxyAttribute.cs index 4795228dcbc7..375a7f4011ad 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/DebuggerTypeProxyAttribute.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/DebuggerTypeProxyAttribute.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable - namespace System.Diagnostics { [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)] @@ -18,15 +16,15 @@ public DebuggerTypeProxyAttribute(Type type) throw new ArgumentNullException(nameof(type)); } - ProxyTypeName = type.AssemblyQualifiedName; + ProxyTypeName = type.AssemblyQualifiedName!; } - public DebuggerTypeProxyAttribute(string? typeName) + public DebuggerTypeProxyAttribute(string typeName) { ProxyTypeName = typeName; } - public string? ProxyTypeName { get; } + public string ProxyTypeName { get; } public Type? Target { diff --git a/src/Common/src/CoreLib/System/Diagnostics/DebuggerVisualizerAttribute.cs b/src/Common/src/CoreLib/System/Diagnostics/DebuggerVisualizerAttribute.cs index dc1fbd252343..48f81203f1a4 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/DebuggerVisualizerAttribute.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/DebuggerVisualizerAttribute.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable - namespace System.Diagnostics { /// @@ -15,18 +13,18 @@ public sealed class DebuggerVisualizerAttribute : Attribute { private Type? _target; - public DebuggerVisualizerAttribute(string? visualizerTypeName) + public DebuggerVisualizerAttribute(string visualizerTypeName) { VisualizerTypeName = visualizerTypeName; } - public DebuggerVisualizerAttribute(string? visualizerTypeName, string? visualizerObjectSourceTypeName) + public DebuggerVisualizerAttribute(string visualizerTypeName, string? visualizerObjectSourceTypeName) { VisualizerTypeName = visualizerTypeName; VisualizerObjectSourceTypeName = visualizerObjectSourceTypeName; } - public DebuggerVisualizerAttribute(string? visualizerTypeName, Type visualizerObjectSource) + public DebuggerVisualizerAttribute(string visualizerTypeName, Type visualizerObjectSource) { if (visualizerObjectSource == null) { @@ -44,7 +42,7 @@ public DebuggerVisualizerAttribute(Type visualizer) throw new ArgumentNullException(nameof(visualizer)); } - VisualizerTypeName = visualizer.AssemblyQualifiedName; + VisualizerTypeName = visualizer.AssemblyQualifiedName!; } public DebuggerVisualizerAttribute(Type visualizer, Type visualizerObjectSource) @@ -58,7 +56,7 @@ public DebuggerVisualizerAttribute(Type visualizer, Type visualizerObjectSource) throw new ArgumentNullException(nameof(visualizerObjectSource)); } - VisualizerTypeName = visualizer.AssemblyQualifiedName; + VisualizerTypeName = visualizer.AssemblyQualifiedName!; VisualizerObjectSourceTypeName = visualizerObjectSource.AssemblyQualifiedName; } @@ -69,13 +67,13 @@ public DebuggerVisualizerAttribute(Type visualizer, string? visualizerObjectSour throw new ArgumentNullException(nameof(visualizer)); } - VisualizerTypeName = visualizer.AssemblyQualifiedName; + VisualizerTypeName = visualizer.AssemblyQualifiedName!; VisualizerObjectSourceTypeName = visualizerObjectSourceTypeName; } public string? VisualizerObjectSourceTypeName { get; } - public string? VisualizerTypeName { get; } + public string VisualizerTypeName { get; } public string? Description { get; set; } diff --git a/src/Common/src/CoreLib/System/Diagnostics/StackFrame.cs b/src/Common/src/CoreLib/System/Diagnostics/StackFrame.cs index a39c35a8a030..1683206bbce0 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/StackFrame.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/StackFrame.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Text; using System.Reflection; diff --git a/src/Common/src/CoreLib/System/Diagnostics/StackTrace.cs b/src/Common/src/CoreLib/System/Diagnostics/StackTrace.cs index fccd9e1cf069..107d4eb79615 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/StackTrace.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/StackTrace.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections; using System.Collections.Generic; using System.Globalization; @@ -227,7 +226,7 @@ internal string ToString(TraceFormat traceFormat) isAsync = typeof(IAsyncStateMachine).IsAssignableFrom(declaringType); if (isAsync || typeof(IEnumerator).IsAssignableFrom(declaringType)) { - methodChanged = TryResolveStateMachineMethod(ref mb!, out declaringType); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + methodChanged = TryResolveStateMachineMethod(ref mb!, out declaringType); // TODO-NULLABLE: Pass non-null string? to string ref (https://github.com/dotnet/roslyn/issues/34874) } } @@ -236,7 +235,7 @@ internal string ToString(TraceFormat traceFormat) if (declaringType != null) { // Append t.FullName, replacing '+' with '.' - string fullName = declaringType.FullName; + string fullName = declaringType.FullName!; for (int i = 0; i < fullName.Length; i++) { char ch = fullName[i]; @@ -386,7 +385,7 @@ private static bool TryResolveStateMachineMethod(ref MethodBase method, out Type // of the original method. Non-iterator async state machines resolve directly to their builder methods // so aren't marked as changed. method = candidateMethod; - declaringType = candidateMethod.DeclaringType; + declaringType = candidateMethod.DeclaringType!; return foundIteratorAttribute; } } diff --git a/src/Common/src/CoreLib/System/Diagnostics/StackTraceHiddenAttribute.cs b/src/Common/src/CoreLib/System/Diagnostics/StackTraceHiddenAttribute.cs index d12a08906d95..474274ac0851 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/StackTraceHiddenAttribute.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/StackTraceHiddenAttribute.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable - namespace System.Diagnostics { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Struct, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Diagnostics/SymbolStore/ISymbolDocumentWriter.cs b/src/Common/src/CoreLib/System/Diagnostics/SymbolStore/ISymbolDocumentWriter.cs index 1db401fcc15a..4980ed76f6cd 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/SymbolStore/ISymbolDocumentWriter.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/SymbolStore/ISymbolDocumentWriter.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Diagnostics.SymbolStore { public interface ISymbolDocumentWriter diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/ActivityTracker.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/ActivityTracker.cs index d0cd84a6ae05..10c4add96348 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/ActivityTracker.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/ActivityTracker.cs @@ -99,7 +99,7 @@ public void OnStart(string providerName, string activityName, int task, ref Guid // Check for recursion, and force-stop any activities if the activity already started. if ((options & EventActivityOptions.Recursive) == 0) { - ActivityInfo existingActivity = FindActiveActivity(fullActivityName, currentActivity); + ActivityInfo? existingActivity = FindActiveActivity(fullActivityName, currentActivity); if (existingActivity != null) { OnStop(providerName, activityName, task, ref activityId); @@ -154,13 +154,13 @@ public void OnStop(string providerName, string activityName, int task, ref Guid for (; ; ) // This is a retry loop. { - ActivityInfo currentActivity = m_current.Value; - ActivityInfo newCurrentActivity = null; // if we have seen any live activities (orphans), at he first one we have seen. + ActivityInfo? currentActivity = m_current.Value; + ActivityInfo? newCurrentActivity = null; // if we have seen any live activities (orphans), at he first one we have seen. // Search to find the activity to stop in one pass. This insures that we don't let one mistake // (stopping something that was not started) cause all active starts to be stopped // By first finding the target start to stop we are more robust. - ActivityInfo activityToStop = FindActiveActivity(fullActivityName, currentActivity); + ActivityInfo? activityToStop = FindActiveActivity(fullActivityName, currentActivity); // ignore stops where we can't find a start because we may have popped them previously. if (activityToStop == null) @@ -175,7 +175,7 @@ public void OnStop(string providerName, string activityName, int task, ref Guid activityId = activityToStop.ActivityId; // See if there are any orphans that need to be stopped. - ActivityInfo orphan = currentActivity; + ActivityInfo? orphan = currentActivity; while (orphan != activityToStop && orphan != null) { if (orphan.m_stopped != 0) // Skip dead activities. @@ -229,7 +229,7 @@ public void Enable() // Catch the not Implemented try { - m_current = new AsyncLocal(ActivityChanging); + m_current = new AsyncLocal(ActivityChanging); } catch (NotImplementedException) { #if (!ES_BUILD_PCL && ! ES_BUILD_PN) @@ -251,9 +251,9 @@ public void Enable() /// /// Searched for a active (nonstopped) activity with the given name. Returns null if not found. /// - private ActivityInfo FindActiveActivity(string name, ActivityInfo startLocation) + private ActivityInfo? FindActiveActivity(string name, ActivityInfo? startLocation) { - var activity = startLocation; + ActivityInfo? activity = startLocation; while (activity != null) { if (name == activity.m_name && activity.m_stopped == 0) @@ -293,7 +293,7 @@ private string NormalizeActivityName(string providerName, string activityName, i /// private class ActivityInfo { - public ActivityInfo(string name, long uniqueId, ActivityInfo creator, Guid activityIDToRestore, EventActivityOptions options) + public ActivityInfo(string name, long uniqueId, ActivityInfo? creator, Guid activityIDToRestore, EventActivityOptions options) { m_name = name; m_eventOptions = options; @@ -314,10 +314,10 @@ public Guid ActivityId } } - public static string Path(ActivityInfo activityInfo) + public static string Path(ActivityInfo? activityInfo) { if (activityInfo == null) - return (""); + return ""; return Path(activityInfo.m_creator) + "/" + activityInfo.m_uniqueId.ToString(); } @@ -326,7 +326,7 @@ public override string ToString() return m_name + "(" + Path(this) + (m_stopped != 0 ? ",DEAD)" : ")"); } - public static string LiveActivities(ActivityInfo list) + public static string LiveActivities(ActivityInfo? list) { if (list == null) return ""; @@ -400,7 +400,7 @@ private unsafe void CreateActivityPathGuid(out Guid idRet, out int activityPathG private unsafe void CreateOverflowGuid(Guid* outPtr) { // Search backwards for an ancestor that has sufficient space to put the ID. - for (ActivityInfo ancestor = m_creator; ancestor != null; ancestor = ancestor.m_creator) + for (ActivityInfo? ancestor = m_creator; ancestor != null; ancestor = ancestor.m_creator) { if (ancestor.m_activityPathGuidOffset <= 10) // we need at least 2 bytes. { @@ -540,7 +540,7 @@ private static unsafe void WriteNibble(ref byte* ptr, byte* endPtr, uint value) readonly internal EventActivityOptions m_eventOptions; // Options passed to start. internal long m_lastChildID; // used to create a unique ID for my children activities internal int m_stopped; // This work item has stopped - readonly internal ActivityInfo m_creator; // My parent (creator). Forms the Path() for the activity. + readonly internal ActivityInfo? m_creator; // My parent (creator). Forms the Path() for the activity. readonly internal Guid m_activityIdToRestore; // The Guid to restore after a stop. #endregion } @@ -548,10 +548,10 @@ private static unsafe void WriteNibble(ref byte* ptr, byte* endPtr, uint value) // This callback is used to initialize the m_current AsyncLocal Variable. // Its job is to keep the ETW Activity ID (part of thread local storage) in sync // with m_current.ActivityID - void ActivityChanging(AsyncLocalValueChangedArgs args) + void ActivityChanging(AsyncLocalValueChangedArgs args) { - ActivityInfo cur = args.CurrentValue; - ActivityInfo prev = args.PreviousValue; + ActivityInfo? cur = args.CurrentValue; + ActivityInfo? prev = args.PreviousValue; // Are we popping off a value? (we have a prev, and it creator is cur) // Then check if we should use the GUID at the time of the start event @@ -592,7 +592,7 @@ void ActivityChanging(AsyncLocalValueChangedArgs args) /// /// This variable points to a linked list that represents all Activities that have started but have not stopped. /// - AsyncLocal m_current; + AsyncLocal? m_current; bool m_checkedForEnable; // Singleton diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/CounterGroup.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/CounterGroup.cs index 0382556f3b56..d669114d502d 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/CounterGroup.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/CounterGroup.cs @@ -48,25 +48,29 @@ private void RegisterCommandCallback() _eventSource.EventCommandExecuted += OnEventSourceCommand; } - private void OnEventSourceCommand(object sender, EventCommandEventArgs e) + private void OnEventSourceCommand(object? sender, EventCommandEventArgs e) { if (e.Command == EventCommand.Enable || e.Command == EventCommand.Update) { string valueStr; float value; + Debug.Assert(e.Arguments != null); + if (e.Arguments.TryGetValue("EventCounterIntervalSec", out valueStr) && float.TryParse(valueStr, out value)) { - // Recursion through EventSource callbacks possible. When we enable the timer - // we synchonously issue a EventSource.Write event, which in turn can call back - // to user code (in an EventListener) while holding this lock. This is dangerous - // because it means this code might inadvertantly participate in a lock loop. - // The scenario seems very unlikely so we ignore that problem for now. lock (this) // Lock the CounterGroup { EnableTimer(value); } } } + else if (e.Command == EventCommand.Disable) + { + lock (this) + { + _pollingIntervalInMilliseconds = 0; + } + } } #endregion // EventSource Command Processing @@ -76,7 +80,7 @@ private void OnEventSourceCommand(object sender, EventCommandEventArgs e) // We need eventCounters to 'attach' themselves to a particular EventSource. // this table provides the mapping from EventSource -> CounterGroup // which represents this 'attached' information. - private static WeakReference[] s_counterGroups; + private static WeakReference[]? s_counterGroups; private static readonly object s_counterGroupsLock = new object(); private static void EnsureEventSourceIndexAvailable(int eventSourceIndex) @@ -100,8 +104,9 @@ internal static CounterGroup GetCounterGroup(EventSource eventSource) { int eventSourceIndex = EventListener.EventSourceIndex(eventSource); EnsureEventSourceIndexAvailable(eventSourceIndex); + Debug.Assert(s_counterGroups != null); WeakReference weakRef = CounterGroup.s_counterGroups[eventSourceIndex]; - CounterGroup ret = null; + CounterGroup? ret = null; if (weakRef == null || !weakRef.TryGetTarget(out ret)) { ret = new CounterGroup(eventSource); @@ -117,7 +122,7 @@ internal static CounterGroup GetCounterGroup(EventSource eventSource) private DateTime _timeStampSinceCollectionStarted; private int _pollingIntervalInMilliseconds; - private Timer _pollingTimer; + private Timer? _pollingTimer; private void DisposeTimer() { @@ -153,7 +158,7 @@ private void EnableTimer(float pollingIntervalInSeconds) restoreFlow = true; } - _pollingTimer = new Timer(s => ((CounterGroup)s).OnTimer(null), this, _pollingIntervalInMilliseconds, _pollingIntervalInMilliseconds); + _pollingTimer = new Timer(s => ((CounterGroup)s!).OnTimer(null), this, _pollingIntervalInMilliseconds, _pollingIntervalInMilliseconds); } finally { @@ -166,7 +171,7 @@ private void EnableTimer(float pollingIntervalInSeconds) OnTimer(null); } - private void OnTimer(object state) + private void OnTimer(object? state) { Debug.WriteLine("Timer fired at " + DateTime.UtcNow.ToString("mm.ss.ffffff")); lock (this) // Lock the CounterGroup @@ -178,7 +183,7 @@ private void OnTimer(object state) foreach (var counter in _counters) { - counter.WritePayload((float)elapsed.TotalSeconds); + counter.WritePayload((float)elapsed.TotalSeconds, _pollingIntervalInMilliseconds); } _timeStampSinceCollectionStarted = now; } @@ -227,4 +232,4 @@ private void OnTimer(Task t, object s) #endregion // Timer Processing } -} \ No newline at end of file +} diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/CounterPayload.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/CounterPayload.cs index 1be7d5494ae9..145dfbfc9267 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/CounterPayload.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/CounterPayload.cs @@ -18,11 +18,11 @@ namespace System.Diagnostics.Tracing #endif { [EventData] - internal class CounterPayload : IEnumerable> + internal class CounterPayload : IEnumerable> { - public string Name { get; set; } + public string? Name { get; set; } - public string DisplayName { get; set; } + public string? DisplayName { get; set; } public double Mean { get; set; } @@ -36,11 +36,15 @@ internal class CounterPayload : IEnumerable> public float IntervalSec { get; internal set; } - public string Metadata { get; set; } + public string? Series { get; set; } + + public string? CounterType { get; set; } + + public string? Metadata { get; set; } #region Implementation of the IEnumerable interface - public IEnumerator> GetEnumerator() + public IEnumerator> GetEnumerator() { return ForEnumeration.GetEnumerator(); } @@ -50,21 +54,21 @@ IEnumerator IEnumerable.GetEnumerator() return ForEnumeration.GetEnumerator(); } - private IEnumerable> ForEnumeration + private IEnumerable> ForEnumeration { get { - yield return new KeyValuePair("Name", Name); - yield return new KeyValuePair("DisplayName", DisplayName); - yield return new KeyValuePair("Mean", Mean); - yield return new KeyValuePair("StandardDeviation", StandardDeviation); - yield return new KeyValuePair("Count", Count); - yield return new KeyValuePair("Min", Min); - yield return new KeyValuePair("Max", Max); - yield return new KeyValuePair("IntervalSec", IntervalSec); - yield return new KeyValuePair("Series", $"Interval={IntervalSec}"); - yield return new KeyValuePair("CounterType", "Mean"); - yield return new KeyValuePair("Metadata", Metadata); + yield return new KeyValuePair("Name", Name); + yield return new KeyValuePair("DisplayName", DisplayName); + yield return new KeyValuePair("Mean", Mean); + yield return new KeyValuePair("StandardDeviation", StandardDeviation); + yield return new KeyValuePair("Count", Count); + yield return new KeyValuePair("Min", Min); + yield return new KeyValuePair("Max", Max); + yield return new KeyValuePair("IntervalSec", IntervalSec); + yield return new KeyValuePair("Series", $"Interval={IntervalSec}"); + yield return new KeyValuePair("CounterType", "Mean"); + yield return new KeyValuePair("Metadata", Metadata); } } @@ -72,23 +76,27 @@ private IEnumerable> ForEnumeration } [EventData] - internal class IncrementingCounterPayload : IEnumerable> + internal class IncrementingCounterPayload : IEnumerable> { - public string Name { get; set; } + public string? Name { get; set; } - public string DisplayName { get; set; } + public string? DisplayName { get; set; } - public string DisplayRateTimeScale { get; set; } + public string? DisplayRateTimeScale { get; set; } public double Increment { get; set; } public float IntervalSec { get; internal set; } - public string Metadata { get; set; } + public string? Metadata { get; set; } + + public string? Series { get; set; } + + public string? CounterType { get; set; } #region Implementation of the IEnumerable interface - public IEnumerator> GetEnumerator() + public IEnumerator> GetEnumerator() { return ForEnumeration.GetEnumerator(); } @@ -98,18 +106,18 @@ IEnumerator IEnumerable.GetEnumerator() return ForEnumeration.GetEnumerator(); } - private IEnumerable> ForEnumeration + private IEnumerable> ForEnumeration { get { - yield return new KeyValuePair("Name", Name); - yield return new KeyValuePair("DisplayName", DisplayName); - yield return new KeyValuePair("DisplayRateTimeScale", DisplayRateTimeScale); - yield return new KeyValuePair("Increment", Increment); - yield return new KeyValuePair("IntervalSec", IntervalSec); - yield return new KeyValuePair("Series", $"Interval={IntervalSec}"); - yield return new KeyValuePair("CounterType", "Sum"); - yield return new KeyValuePair("Metadata", Metadata); + yield return new KeyValuePair("Name", Name); + yield return new KeyValuePair("DisplayName", DisplayName); + yield return new KeyValuePair("DisplayRateTimeScale", DisplayRateTimeScale); + yield return new KeyValuePair("Increment", Increment); + yield return new KeyValuePair("IntervalSec", IntervalSec); + yield return new KeyValuePair("Series", $"Interval={IntervalSec}"); + yield return new KeyValuePair("CounterType", "Sum"); + yield return new KeyValuePair("Metadata", Metadata); } } diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/DiagnosticCounter.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/DiagnosticCounter.cs index ea4cb92612b1..af48288f9ae7 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/DiagnosticCounter.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/DiagnosticCounter.cs @@ -30,7 +30,7 @@ public abstract class DiagnosticCounter : IDisposable /// /// The name. /// The event source. - public DiagnosticCounter(string name, EventSource eventSource) + internal DiagnosticCounter(string name, EventSource eventSource) { if (name == null) { @@ -59,7 +59,7 @@ public void Dispose() if (_group != null) { _group.Remove(this); - _group = null; + _group = null!; // TODO-NULLABLE: Avoid nulling out in Dispose } } @@ -75,7 +75,7 @@ public void AddMetadata(string key, string value) } } - public string DisplayName { get; set; } + public string? DisplayName { get; set; } public string Name { get; } @@ -84,9 +84,9 @@ public void AddMetadata(string key, string value) #region private implementation private CounterGroup _group; - private Dictionary _metadata; + private Dictionary? _metadata; - internal abstract void WritePayload(float intervalSec); + internal abstract void WritePayload(float intervalSec, int pollingIntervalMillisec); // arbitrarily we use name as the lock object. internal object MyLock { get { return Name; } } diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventCounter.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventCounter.cs index a9fc0895c9a8..bfe05525831e 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventCounter.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventCounter.cs @@ -83,7 +83,7 @@ internal void OnMetricWritten(double value) _count++; } - internal override void WritePayload(float intervalSec) + internal override void WritePayload(float intervalSec, int pollingIntervalMillisec) { lock (MyLock) { @@ -103,7 +103,8 @@ internal override void WritePayload(float intervalSec) } payload.Min = _min; payload.Max = _max; - + payload.Series = $"Interval={pollingIntervalMillisec}"; // TODO: This may need to change when we support multi-session + payload.CounterType = "Mean"; payload.Metadata = GetMetadataString(); payload.DisplayName = DisplayName; payload.Name = Name; @@ -111,6 +112,7 @@ internal override void WritePayload(float intervalSec) EventSource.Write("EventCounters", new EventSourceOptions() { Level = EventLevel.LogAlways }, new CounterPayloadType(payload)); } } + private void ResetStatistics() { Debug.Assert(Monitor.IsEntered(MyLock)); @@ -127,7 +129,7 @@ private void ResetStatistics() private const int BufferedSize = 10; private const double UnusedBufferSlotValue = double.NegativeInfinity; private const int UnsetIndex = -1; - private volatile double[] _bufferedValues; + private volatile double[] _bufferedValues = null!; private volatile int _bufferedValuesIndex; private void InitializeBuffer() diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventDescriptor.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventDescriptor.cs index 53017b70602d..f3d4dbce3524 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventDescriptor.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventDescriptor.cs @@ -176,7 +176,7 @@ internal int TraceLoggingId } } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is EventDescriptor)) return false; diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventProvider.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventProvider.cs index a8622a8fb817..fde1b47d4449 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventProvider.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventProvider.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. + using Microsoft.Win32; using System.Collections.Generic; using System.Diagnostics; @@ -93,14 +94,14 @@ internal SessionInfo(int sessionIdBit_, int etwSessionId_) } internal IEventProvider m_eventProvider; // The interface that implements the specific logging mechanism functions. - Interop.Advapi32.EtwEnableCallback m_etwCallback; // Trace Callback function + Interop.Advapi32.EtwEnableCallback? m_etwCallback; // Trace Callback function private long m_regHandle; // Trace Registration Handle private byte m_level; // Tracing Level private long m_anyKeywordMask; // Trace Enable Flags private long m_allKeywordMask; // Match all keyword - private List m_liveSessions; // current live sessions (Tuple) + private List? m_liveSessions; // current live sessions (Tuple) private bool m_enabled; // Enabled flag from Trace callback - private string m_providerName; // Control name + private string? m_providerName; // Control name private Guid m_providerId; // Control Guid internal bool m_disposed; // when true provider has unregistered @@ -277,7 +278,7 @@ unsafe void EtwEnableCallBack( try { ControllerCommand command = ControllerCommand.Update; - IDictionary args = null; + IDictionary? args = null; bool skipFinalOnControllerCommand = false; if (controlCode == Interop.Advapi32.EVENT_CONTROL_CODE_ENABLE_PROVIDER) { @@ -315,12 +316,13 @@ unsafe void EtwEnableCallBack( filterData = null; // read filter data only when a session is being *added* - byte[] data; + byte[]? data; int keyIndex; if (bEnabling && GetDataFromController(etwSessionId, filterData, out command, out data, out keyIndex)) { args = new Dictionary(4); + Debug.Assert(data != null); while (keyIndex < data.Length) { int keyEnd = FindNull(data, keyIndex); @@ -366,7 +368,7 @@ unsafe void EtwEnableCallBack( } // New in CLR4.0 - protected virtual void OnControllerCommand(ControllerCommand command, IDictionary arguments, int sessionId, int etwSessionId) { } + protected virtual void OnControllerCommand(ControllerCommand command, IDictionary? arguments, int sessionId, int etwSessionId) { } protected EventLevel Level { get { return (EventLevel)m_level; } set { m_level = (byte)value; } } protected EventKeywords MatchAnyKeyword { get { return (EventKeywords)m_anyKeywordMask; } set { m_anyKeywordMask = unchecked((long)value); } } protected EventKeywords MatchAllKeyword { get { return (EventKeywords)m_allKeywordMask; } set { m_allKeywordMask = unchecked((long)value); } } @@ -390,10 +392,10 @@ private static int FindNull(byte[] buffer, int idx) /// private List> GetSessions() { - List liveSessionList = null; + List? liveSessionList = null; GetSessionInfo( - (int etwSessionId, long matchAllKeywords, ref List sessionList) => + (int etwSessionId, long matchAllKeywords, ref List? sessionList) => GetSessionInfoCallback(etwSessionId, matchAllKeywords, ref sessionList), ref liveSessionList); @@ -407,7 +409,7 @@ private List> GetSessions() { int idx; if ((idx = IndexOfSessionInList(liveSessionList, s.etwSessionId)) < 0 || - (liveSessionList[idx].sessionIdBit != s.sessionIdBit)) + (liveSessionList![idx].sessionIdBit != s.sessionIdBit)) changedSessionList.Add(Tuple.Create(s, false)); } @@ -420,7 +422,7 @@ private List> GetSessions() { int idx; if ((idx = IndexOfSessionInList(m_liveSessions, s.etwSessionId)) < 0 || - (m_liveSessions[idx].sessionIdBit != s.sessionIdBit)) + (m_liveSessions![idx].sessionIdBit != s.sessionIdBit)) changedSessionList.Add(Tuple.Create(s, true)); } } @@ -435,7 +437,7 @@ private List> GetSessions() /// GetSessionInfo() passes in. /// private static void GetSessionInfoCallback(int etwSessionId, long matchAllKeywords, - ref List sessionList) + ref List? sessionList) { uint sessionIdBitMask = (uint)SessionMask.FromEventKeywords(unchecked((ulong)matchAllKeywords)); // an ETW controller that specifies more than the mandated bit for our EventSource @@ -461,14 +463,14 @@ private static void GetSessionInfoCallback(int etwSessionId, long matchAllKeywor sessionList.Add(new SessionInfo(val + 1, etwSessionId)); } - private delegate void SessionInfoCallback(int etwSessionId, long matchAllKeywords, ref List sessionList); + private delegate void SessionInfoCallback(int etwSessionId, long matchAllKeywords, ref List? sessionList); /// /// This method enumerates over all active ETW sessions that have enabled 'this.m_Guid' /// for the current process ID, calling 'action' for each session, and passing it the /// ETW session and the 'AllKeywords' the session enabled for the current provider. /// - private unsafe void GetSessionInfo(SessionInfoCallback action, ref List sessionList) + private unsafe void GetSessionInfo(SessionInfoCallback action, ref List? sessionList) { // We wish the EventSource package to be legal for Windows Store applications. // Currently EnumerateTraceGuidsEx is not an allowed API, so we avoid its use here @@ -578,7 +580,7 @@ private unsafe void GetSessionInfo(SessionInfoCallback action, ref List - private static int IndexOfSessionInList(List sessions, int etwSessionId) + private static int IndexOfSessionInList(List? sessions, int etwSessionId) { if (sessions == null) return -1; @@ -600,7 +602,7 @@ private static int IndexOfSessionInList(List sessions, int etwSessi /// starts, and the command being issued associated with that data. /// private unsafe bool GetDataFromController(int etwSessionId, - Interop.Advapi32.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[] data, out int dataStart) + Interop.Advapi32.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[]? data, out int dataStart) { data = null; dataStart = 0; @@ -727,7 +729,7 @@ private static void SetLastError(WriteEventErrorCode error) // // // - private static unsafe object EncodeObject(ref object data, ref EventData* dataDescriptor, ref byte* dataBuffer, ref uint totalEventSize) + private static unsafe object? EncodeObject(ref object data, ref EventData* dataDescriptor, ref byte* dataBuffer, ref uint totalEventSize) /*++ Routine Description: @@ -753,8 +755,8 @@ to fill the passed in ETW data descriptor. Again: dataDescriptor->Reserved = 0; - string sRet = data as string; - byte[] blobRet = null; + string? sRet = data as string; + byte[]? blobRet = null; if (sRet != null) { @@ -921,7 +923,7 @@ to fill the passed in ETW data descriptor. if (data == null) sRet = ""; else - sRet = data.ToString(); + sRet = data.ToString()!; dataDescriptor->Size = ((uint)sRet.Length + 1) * 2; } @@ -931,7 +933,7 @@ to fill the passed in ETW data descriptor. dataDescriptor++; dataBuffer += s_basicTypeAllocationBufferSize; - return (object)sRet ?? (object)blobRet; + return (object?)sRet ?? (object?)blobRet; } /// @@ -989,7 +991,7 @@ internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, IntPtr even int index; int refObjIndex = 0; List refObjPosition = new List(s_etwAPIMaxRefObjCount); - List dataRefObj = new List(s_etwAPIMaxRefObjCount); + List dataRefObj = new List(s_etwAPIMaxRefObjCount); EventData* userData = stackalloc EventData[2 * argCount]; for (int i = 0; i < 2 * argCount; i++) userData[i] = default; @@ -1008,8 +1010,7 @@ internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, IntPtr even { if (eventPayload[index] != null) { - object supportedRefObj; - supportedRefObj = EncodeObject(ref eventPayload[index], ref userDataPtr, ref currentBuffer, ref totalEventSize); + object? supportedRefObj = EncodeObject(ref eventPayload[index], ref userDataPtr, ref currentBuffer, ref totalEventSize); if (supportedRefObj != null) { @@ -1061,8 +1062,8 @@ internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, IntPtr even // // now fix any string arguments and set the pointer on the data descriptor // - fixed (char* v0 = (string)dataRefObj[0], v1 = (string)dataRefObj[1], v2 = (string)dataRefObj[2], v3 = (string)dataRefObj[3], - v4 = (string)dataRefObj[4], v5 = (string)dataRefObj[5], v6 = (string)dataRefObj[6], v7 = (string)dataRefObj[7]) + fixed (char* v0 = (string?)dataRefObj[0], v1 = (string?)dataRefObj[1], v2 = (string?)dataRefObj[2], v3 = (string?)dataRefObj[3], + v4 = (string?)dataRefObj[4], v5 = (string?)dataRefObj[5], v6 = (string?)dataRefObj[6], v7 = (string?)dataRefObj[7]) { userDataPtr = (EventData*)userData; if (dataRefObj[0] != null) @@ -1114,12 +1115,12 @@ internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, IntPtr even rgGCHandle[i] = GCHandle.Alloc(dataRefObj[i], GCHandleType.Pinned); if (dataRefObj[i] is string) { - fixed (char* p = (string)dataRefObj[i]) + fixed (char* p = (string?)dataRefObj[i]) userDataPtr[refObjPosition[i]].Ptr = (ulong)p; } else { - fixed (byte* p = (byte[])dataRefObj[i]) + fixed (byte* p = (byte[]?)dataRefObj[i]) userDataPtr[refObjPosition[i]].Ptr = (ulong)p; } } diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventSource.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventSource.cs index 50343b4c5f3d..6412676f26ee 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventSource.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventSource.cs @@ -164,7 +164,6 @@ // opportunity to expose this format to EventListeners in the future. // using System; -using System.Runtime.CompilerServices; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; @@ -242,7 +241,7 @@ public partial class EventSource : IDisposable { #if FEATURE_EVENTSOURCE_XPLAT - private static readonly EventListener persistent_Xplat_Listener = XplatEventLogger.InitializePersistentListener(); + private static readonly EventListener? persistent_Xplat_Listener = XplatEventLogger.InitializePersistentListener(); #endif //FEATURE_EVENTSOURCE_XPLAT /// @@ -320,7 +319,7 @@ public static Guid GetGuid(Type eventSourceType) if (eventSourceType == null) throw new ArgumentNullException(nameof(eventSourceType)); - EventSourceAttribute attrib = (EventSourceAttribute)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute)); + EventSourceAttribute? attrib = (EventSourceAttribute?)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute)); string name = eventSourceType.Name; if (attrib != null) { @@ -366,7 +365,7 @@ public static string GetName(Type eventSourceType) /// The manifest XML fragment contains the string name of the DLL name in /// which it is embedded. This parameter specifies what name will be used /// The XML data string - public static string GenerateManifest(Type eventSourceType, string assemblyPathToIncludeInManifest) + public static string? GenerateManifest(Type eventSourceType, string? assemblyPathToIncludeInManifest) { return GenerateManifest(eventSourceType, assemblyPathToIncludeInManifest, EventManifestOptions.None); } @@ -382,12 +381,12 @@ public static string GenerateManifest(Type eventSourceType, string assemblyPathT /// The flags to customize manifest generation. If flags has bit OnlyIfNeededForRegistration specified /// this returns null when the eventSourceType does not require explicit registration /// The XML data string or null - public static string GenerateManifest(Type eventSourceType, string assemblyPathToIncludeInManifest, EventManifestOptions flags) + public static string? GenerateManifest(Type eventSourceType, string? assemblyPathToIncludeInManifest, EventManifestOptions flags) { if (eventSourceType == null) throw new ArgumentNullException(nameof(eventSourceType)); - byte[] manifestBytes = EventSource.CreateManifestAndDescriptors(eventSourceType, assemblyPathToIncludeInManifest, null, flags); + byte[]? manifestBytes = EventSource.CreateManifestAndDescriptors(eventSourceType, assemblyPathToIncludeInManifest, null, flags); return (manifestBytes == null) ? null : Encoding.UTF8.GetString(manifestBytes, 0, manifestBytes.Length); } @@ -401,6 +400,8 @@ public static IEnumerable GetSources() var ret = new List(); lock (EventListener.EventListenersLock) { + Debug.Assert(EventListener.s_EventSources != null); + foreach (WeakReference eventSourceRef in EventListener.s_EventSources) { if (eventSourceRef.Target is EventSource eventSource && !eventSource.IsDisposed) @@ -419,7 +420,7 @@ public static IEnumerable GetSources() /// The instance of EventSource to send the command to /// A positive user-defined EventCommand, or EventCommand.SendManifest /// A set of (name-argument, value-argument) pairs associated with the command - public static void SendCommand(EventSource eventSource, EventCommand command, IDictionary commandArguments) + public static void SendCommand(EventSource eventSource, EventCommand command, IDictionary? commandArguments) { if (eventSource == null) throw new ArgumentNullException(nameof(eventSource)); @@ -443,7 +444,7 @@ public static void SendCommand(EventSource eventSource, EventCommand command, ID /// The event source constructor does not throw exceptions. Instead we remember any exception that /// was generated (it is also logged to Trace.WriteLine). /// - public Exception ConstructionException { get { return m_constructionException; } } + public Exception? ConstructionException { get { return m_constructionException; } } /// /// EventSources can have arbitrary string key-value pairs associated with them called Traits. @@ -453,7 +454,7 @@ public static void SendCommand(EventSource eventSource, EventCommand command, ID /// /// The key to look up in the set of key-value pairs passed to the EventSource constructor /// The value string associated with key. Will return null if there is no such key. - public string GetTrait(string key) + public string? GetTrait(string key) { if (m_traits != null) { @@ -463,6 +464,7 @@ public string GetTrait(string key) return m_traits[i + 1]; } } + return null; } @@ -485,7 +487,7 @@ public event EventHandler EventCommandExecuted // If we have an EventHandler attached to the EventSource before the first command arrives // It should get a chance to handle the deferred commands. - EventCommandEventArgs deferredCommands = m_deferredCommands; + EventCommandEventArgs? deferredCommands = m_deferredCommands; while (deferredCommands != null) { value(this, deferredCommands); @@ -658,15 +660,15 @@ protected EventSource(EventSourceSettings settings) : this(settings, null) { } /// /// See EventSourceSettings for more. /// A collection of key-value strings (must be an even number). - protected EventSource(EventSourceSettings settings, params string[] traits) + protected EventSource(EventSourceSettings settings, params string[]? traits) { m_config = ValidateSettings(settings); Guid eventSourceGuid; - string eventSourceName; + string? eventSourceName; - EventMetadata[] eventDescriptors; - byte[] manifest; + EventMetadata[]? eventDescriptors; + byte[]? manifest; GetMetadata(out eventSourceGuid, out eventSourceName, out eventDescriptors, out manifest); if (eventSourceGuid.Equals(Guid.Empty) || eventSourceName == null) @@ -700,7 +702,7 @@ private unsafe void DefineEventPipeEvents() if (eventID == 0) continue; - byte[] metadata = EventPipeMetadataGenerator.Instance.GenerateEventMetadata(m_eventData[i]); + byte[]? metadata = EventPipeMetadataGenerator.Instance.GenerateEventMetadata(m_eventData[i]); uint metadataLength = (metadata != null) ? (uint)metadata.Length : 0; string eventName = m_eventData[i].Name; @@ -726,7 +728,7 @@ private unsafe void DefineEventPipeEvents() } #endif - internal virtual void GetMetadata(out Guid eventSourceGuid, out string eventSourceName, out EventMetadata[] eventData, out byte[] manifestBytes) + internal virtual void GetMetadata(out Guid eventSourceGuid, out string? eventSourceName, out EventMetadata[]? eventData, out byte[]? manifestBytes) { // // In ProjectN subclasses need to override this method, and return the data from their EventSourceAttribute and EventAttribute annotations. @@ -858,7 +860,7 @@ protected unsafe void WriteEvent(int eventId, long arg1, long arg2, long arg3) // optimized for common signatures (strings) [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] - protected unsafe void WriteEvent(int eventId, string arg1) + protected unsafe void WriteEvent(int eventId, string? arg1) { if (m_eventSourceEnabled) { @@ -875,7 +877,7 @@ protected unsafe void WriteEvent(int eventId, string arg1) } [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] - protected unsafe void WriteEvent(int eventId, string arg1, string arg2) + protected unsafe void WriteEvent(int eventId, string? arg1, string? arg2) { if (m_eventSourceEnabled) { @@ -897,7 +899,7 @@ protected unsafe void WriteEvent(int eventId, string arg1, string arg2) } [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] - protected unsafe void WriteEvent(int eventId, string arg1, string arg2, string arg3) + protected unsafe void WriteEvent(int eventId, string? arg1, string? arg2, string? arg3) { if (m_eventSourceEnabled) { @@ -925,7 +927,7 @@ protected unsafe void WriteEvent(int eventId, string arg1, string arg2, string a // optimized for common signatures (string and ints) [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] - protected unsafe void WriteEvent(int eventId, string arg1, int arg2) + protected unsafe void WriteEvent(int eventId, string? arg1, int arg2) { if (m_eventSourceEnabled) { @@ -945,7 +947,7 @@ protected unsafe void WriteEvent(int eventId, string arg1, int arg2) } [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] - protected unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3) + protected unsafe void WriteEvent(int eventId, string? arg1, int arg2, int arg3) { if (m_eventSourceEnabled) { @@ -969,7 +971,7 @@ protected unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3) // optimized for common signatures (string and longs) [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] - protected unsafe void WriteEvent(int eventId, string arg1, long arg2) + protected unsafe void WriteEvent(int eventId, string? arg1, long arg2) { if (m_eventSourceEnabled) { @@ -990,7 +992,7 @@ protected unsafe void WriteEvent(int eventId, string arg1, long arg2) // optimized for common signatures (long and string) [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] - protected unsafe void WriteEvent(int eventId, long arg1, string arg2) + protected unsafe void WriteEvent(int eventId, long arg1, string? arg2) { if (m_eventSourceEnabled) { @@ -1011,7 +1013,7 @@ protected unsafe void WriteEvent(int eventId, long arg1, string arg2) // optimized for common signatures (int and string) [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] - protected unsafe void WriteEvent(int eventId, int arg1, string arg2) + protected unsafe void WriteEvent(int eventId, int arg1, string? arg2) { if (m_eventSourceEnabled) { @@ -1031,7 +1033,7 @@ protected unsafe void WriteEvent(int eventId, int arg1, string arg2) } [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] - protected unsafe void WriteEvent(int eventId, byte[] arg1) + protected unsafe void WriteEvent(int eventId, byte[]? arg1) { if (m_eventSourceEnabled) { @@ -1065,7 +1067,7 @@ protected unsafe void WriteEvent(int eventId, byte[] arg1) } [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] - protected unsafe void WriteEvent(int eventId, long arg1, byte[] arg2) + protected unsafe void WriteEvent(int eventId, long arg1, byte[]? arg2) { if (m_eventSourceEnabled) { @@ -1212,9 +1214,9 @@ protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid* rel { if (m_eventSourceEnabled) { + Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source. try { - Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source. if (relatedActivityId != null) ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name); @@ -1260,7 +1262,7 @@ protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid* rel } else { - TraceLoggingEventTypes tlet = m_eventData[eventId].TraceLoggingEventTypes; + TraceLoggingEventTypes? tlet = m_eventData[eventId].TraceLoggingEventTypes; if (tlet == null) { tlet = new TraceLoggingEventTypes(m_eventData[eventId].Name, @@ -1362,14 +1364,14 @@ protected virtual void Dispose(bool disposing) if (m_etwProvider != null) { m_etwProvider.Dispose(); - m_etwProvider = null; + m_etwProvider = null!; // TODO-NULLABLE: Avoid nulling out in Dispose } #endif #if FEATURE_PERFTRACING if (m_eventPipeProvider != null) { m_eventPipeProvider.Dispose(); - m_eventPipeProvider = null; + m_eventPipeProvider = null!; // TODO-NULLABLE: Avoid nulling out in Dispose } #endif } @@ -1388,7 +1390,7 @@ protected virtual void Dispose(bool disposing) #region private private unsafe void WriteEventRaw( - string eventName, + string? eventName, ref EventDescriptor eventDescriptor, IntPtr eventHandle, Guid* activityID, @@ -1427,7 +1429,7 @@ internal EventSource(Guid eventSourceGuid, string eventSourceName) { } // Used by the internal FrameworkEventSource constructor and the TraceLogging-style event source constructor - internal EventSource(Guid eventSourceGuid, string eventSourceName, EventSourceSettings settings, string[] traits = null) + internal EventSource(Guid eventSourceGuid, string eventSourceName, EventSourceSettings settings, string[]? traits = null) { m_config = ValidateSettings(settings); Initialize(eventSourceGuid, eventSourceName, traits); @@ -1440,7 +1442,7 @@ internal EventSource(Guid eventSourceGuid, string eventSourceName, EventSourceSe /// member, and any future access to the "Log" would throw the cached exception). /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")] - private unsafe void Initialize(Guid eventSourceGuid, string eventSourceName, string[] traits) + private unsafe void Initialize(Guid eventSourceGuid, string eventSourceName, string[]? traits) { try { @@ -1536,7 +1538,7 @@ private unsafe void Initialize(Guid eventSourceGuid, string eventSourceName, str // This is the most likely place for exceptions to happen. // Note that we are NOT resetting m_deferredCommands to NULL here, // We are giving for EventHandler that will be attached later - EventCommandEventArgs deferredCommands = m_deferredCommands; + EventCommandEventArgs? deferredCommands = m_deferredCommands; while (deferredCommands != null) { DoCommand(deferredCommands); // This can never throw, it catches them and reports the errors. @@ -1550,7 +1552,7 @@ private static string GetName(Type eventSourceType, EventManifestOptions flags) if (eventSourceType == null) throw new ArgumentNullException(nameof(eventSourceType)); - EventSourceAttribute attrib = (EventSourceAttribute)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags); + EventSourceAttribute? attrib = (EventSourceAttribute?)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags); if (attrib != null && attrib.Name != null) return attrib.Name; @@ -1732,14 +1734,14 @@ private static Guid GenerateGuidFromName(string name) hash.Start(); hash.Append(namespaceBytes); hash.Append(bytes); - Array.Resize(ref bytes, 16); + Array.Resize(ref bytes!, 16); // TODO-NULLABLE: Remove ! when nullable attributes are respected hash.Finish(bytes); bytes[7] = unchecked((byte)((bytes[7] & 0x0F) | 0x50)); // Set high 4 bits of octet 7 to 5, as per RFC 4122 return new Guid(bytes); } - private unsafe object DecodeObject(int eventId, int parameterId, ref EventSource.EventData* data) + private unsafe object? DecodeObject(int eventId, int parameterId, ref EventSource.EventData* data) { // TODO FIX : We use reflection which in turn uses EventSource, right now we carefully avoid // the recursion, but can we do this in a robust way? @@ -1748,6 +1750,7 @@ private unsafe object DecodeObject(int eventId, int parameterId, ref EventSource // advance to next EventData in array ++data; + Debug.Assert(m_eventData != null); Type dataType = GetDataType(m_eventData[eventId], parameterId); Again: @@ -1884,9 +1887,9 @@ private unsafe object DecodeObject(int eventId, int parameterId, ref EventSource // Finds the Dispatcher (which holds the filtering state), for a given dispatcher for the current // eventSource). - private EventDispatcher GetDispatcher(EventListener listener) + private EventDispatcher? GetDispatcher(EventListener? listener) { - EventDispatcher dispatcher = m_Dispatchers; + EventDispatcher? dispatcher = m_Dispatchers; while (dispatcher != null) { if (dispatcher.m_Listener == listener) @@ -1900,9 +1903,9 @@ private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object { if (m_eventSourceEnabled) { + Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source. try { - Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source. if (childActivityID != null) { ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name); @@ -1965,7 +1968,7 @@ private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object } else { - TraceLoggingEventTypes tlet = m_eventData[eventId].TraceLoggingEventTypes; + TraceLoggingEventTypes? tlet = m_eventData[eventId].TraceLoggingEventTypes; if (tlet == null) { tlet = new TraceLoggingEventTypes(m_eventData[eventId].Name, @@ -2003,7 +2006,7 @@ private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object else #endif // !ES_BUILD_STANDALONE { - object[] serializedArgs = SerializeEventArgs(eventId, args); + object?[] serializedArgs = SerializeEventArgs(eventId, args); WriteToAllListeners( eventId: eventId, osThreadId: null, @@ -2024,9 +2027,10 @@ private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object } } - private unsafe object[] SerializeEventArgs(int eventId, object[] args) + private unsafe object?[] SerializeEventArgs(int eventId, object?[] args) { - TraceLoggingEventTypes eventTypes = m_eventData[eventId].TraceLoggingEventTypes; + Debug.Assert(m_eventData != null); + TraceLoggingEventTypes? eventTypes = m_eventData[eventId].TraceLoggingEventTypes; if (eventTypes == null) { eventTypes = new TraceLoggingEventTypes(m_eventData[eventId].Name, @@ -2034,7 +2038,7 @@ private unsafe object[] SerializeEventArgs(int eventId, object[] args) m_eventData[eventId].Parameters); Interlocked.CompareExchange(ref m_eventData[eventId].TraceLoggingEventTypes, eventTypes, null); } - var eventData = new object[eventTypes.typeInfos.Length]; + var eventData = new object?[eventTypes.typeInfos.Length]; for (int i = 0; i < eventTypes.typeInfos.Length; i++) { eventData[i] = eventTypes.typeInfos[i].GetData(args[i]); @@ -2083,6 +2087,7 @@ private void LogEventArgsMismatches(ParameterInfo[] infos, object[] args) private unsafe void WriteToAllListeners(int eventId, Guid* activityID, Guid* childActivityID, int eventDataCount, EventSource.EventData* data) { + Debug.Assert(m_eventData != null); // We represent a byte[] as a integer denoting the length and then a blob of bytes in the data pointer. This causes a spurious // warning because eventDataCount is off by one for the byte[] case since a byte[] has 2 items associated it. So we want to check // that the number of parameters is correct against the byte[] case, but also we the args array would be one too long if @@ -2107,7 +2112,7 @@ private unsafe void WriteToAllListeners(int eventId, Guid* activityID, Guid* chi paramCount = Math.Min(paramCount, eventDataCount); } - object[] args = new object[paramCount]; + object?[] args = new object[paramCount]; EventSource.EventData* dataPtr = data; for (int i = 0; i < paramCount; i++) @@ -2122,7 +2127,7 @@ private unsafe void WriteToAllListeners(int eventId, Guid* activityID, Guid* chi } // helper for writing to all EventListeners attached the current eventSource. - internal unsafe void WriteToAllListeners(int eventId, uint* osThreadId, DateTime* timeStamp, Guid* activityID, Guid* childActivityID, params object[] args) + internal unsafe void WriteToAllListeners(int eventId, uint* osThreadId, DateTime* timeStamp, Guid* activityID, Guid* childActivityID, params object?[] args) { EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this); eventCallbackArgs.EventId = eventId; @@ -2134,17 +2139,19 @@ internal unsafe void WriteToAllListeners(int eventId, uint* osThreadId, DateTime eventCallbackArgs.ActivityId = *activityID; if (childActivityID != null) eventCallbackArgs.RelatedActivityId = *childActivityID; + + Debug.Assert(m_eventData != null); eventCallbackArgs.EventName = m_eventData[eventId].Name; eventCallbackArgs.Message = m_eventData[eventId].Message; - eventCallbackArgs.Payload = new ReadOnlyCollection(args); + eventCallbackArgs.Payload = new ReadOnlyCollection(args); DispatchToAllListeners(eventId, childActivityID, eventCallbackArgs); } private unsafe void DispatchToAllListeners(int eventId, Guid* childActivityID, EventWrittenEventArgs eventCallbackArgs) { - Exception lastThrownException = null; - for (EventDispatcher dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) + Exception? lastThrownException = null; + for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) { Debug.Assert(dispatcher.m_EventEnabled != null); if (eventId == -1 || dispatcher.m_EventEnabled[eventId]) @@ -2225,11 +2232,11 @@ private void WriteStringToAllListeners(string eventName, string msg) EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this); eventCallbackArgs.EventId = 0; eventCallbackArgs.Message = msg; - eventCallbackArgs.Payload = new ReadOnlyCollection(new List() { msg }); + eventCallbackArgs.Payload = new ReadOnlyCollection(new List() { msg }); eventCallbackArgs.PayloadNames = new ReadOnlyCollection(new List { "message" }); eventCallbackArgs.EventName = eventName; - for (EventDispatcher dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) + for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) { bool dispatcherEnabled = false; if (dispatcher.m_EventEnabled == null) @@ -2272,6 +2279,7 @@ private bool IsEnabledByDefault(int eventNum, bool enable, EventLevel currentLev if (!enable) return false; + Debug.Assert(m_eventData != null); EventLevel eventLevel = (EventLevel)m_eventData[eventNum].Descriptor.Level; EventKeywords eventKeywords = unchecked((EventKeywords)((ulong)m_eventData[eventNum].Descriptor.Keywords & (~(SessionMask.All.ToEventKeywords())))); @@ -2316,7 +2324,7 @@ private bool IsEnabledCommon(bool enabled, EventLevel currentLevel, EventKeyword } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] - private void ThrowEventSourceException(string eventName, Exception innerEx = null) + private void ThrowEventSourceException(string? eventName, Exception? innerEx = null) { // If we fail during out of band logging we may end up trying // to throw another EventSourceException, thus hitting a StackOverflowException. @@ -2370,7 +2378,7 @@ private void ThrowEventSourceException(string eventName, Exception innerEx = nul } } - private void ValidateEventOpcodeForTransfer(ref EventMetadata eventData, string eventName) + private void ValidateEventOpcodeForTransfer(ref EventMetadata eventData, string? eventName) { if ((EventOpcode)eventData.Descriptor.Opcode != EventOpcode.Send && (EventOpcode)eventData.Descriptor.Opcode != EventOpcode.Receive && @@ -2380,7 +2388,7 @@ private void ValidateEventOpcodeForTransfer(ref EventMetadata eventData, string } } - internal static EventOpcode GetOpcodeWithDefault(EventOpcode opcode, string eventName) + internal static EventOpcode GetOpcodeWithDefault(EventOpcode opcode, string? eventName) { if (opcode == EventOpcode.Info && eventName != null) { @@ -2409,11 +2417,11 @@ public OverideEventProvider(EventSource eventSource, EventProviderType providerT this.m_eventSource = eventSource; this.m_eventProviderType = providerType; } - protected override void OnControllerCommand(ControllerCommand command, IDictionary arguments, + protected override void OnControllerCommand(ControllerCommand command, IDictionary? arguments, int perEventSourceSessionId, int etwSessionId) { // We use null to represent the ETW EventListener. - EventListener listener = null; + EventListener? listener = null; m_eventSource.SendCommand(listener, m_eventProviderType, perEventSourceSessionId, etwSessionId, (EventCommand)command, IsEnabled(), Level, MatchAnyKeyword, arguments); } @@ -2462,7 +2470,7 @@ public EventMetadata(EventDescriptor descriptor, this.TriggersActivityTracking = 0; this.Name = name; this.Message = message; - this.Parameters = null; + this.Parameters = null!; this.TraceLoggingEventTypes = null; this.ActivityOptions = EventActivityOptions.None; this.ParameterTypes = parameterTypes; @@ -2485,10 +2493,10 @@ public EventMetadata(EventDescriptor descriptor, public byte TriggersActivityTracking; // count of listeners that marked this event as trigger for start of activity logging. #pragma warning restore 0649 public string Name; // the name of the event - public string Message; // If the event has a message associated with it, this is it. + public string? Message; // If the event has a message associated with it, this is it. public ParameterInfo[] Parameters; // TODO can we remove? - public TraceLoggingEventTypes TraceLoggingEventTypes; + public TraceLoggingEventTypes? TraceLoggingEventTypes; public EventActivityOptions ActivityOptions; #if ES_BUILD_PN @@ -2599,7 +2607,7 @@ private Type EventTypeToType(EventParameterType type) return typeof(string); default: // TODO: should I throw an exception here? - return null; + return null!; } } #endif @@ -2630,10 +2638,10 @@ private Type EventTypeToType(EventParameterType type) // * The 'enabled' 'level', matchAnyKeyword' arguments are ignored (must be true, 0, 0). // // dispatcher == null has special meaning. It is the 'ETW' dispatcher. - internal void SendCommand(EventListener listener, EventProviderType eventProviderType, int perEventSourceSessionId, int etwSessionId, + internal void SendCommand(EventListener? listener, EventProviderType eventProviderType, int perEventSourceSessionId, int etwSessionId, EventCommand command, bool enable, EventLevel level, EventKeywords matchAnyKeyword, - IDictionary commandArguments) + IDictionary? commandArguments) { var commandArgs = new EventCommandEventArgs(command, commandArguments, this, listener, eventProviderType, perEventSourceSessionId, etwSessionId, enable, level, matchAnyKeyword); lock (EventListener.EventListenersLock) @@ -2784,8 +2792,10 @@ internal void DoCommand(EventCommandEventArgs commandArgs) for (int i = 0; i < m_eventData.Length; i++) { bool isEnabledForAnyListener = false; - for (EventDispatcher dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) + for (EventDispatcher? dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) { + Debug.Assert(dispatcher.m_EventEnabled != null); + if (dispatcher.m_EventEnabled[i]) { isEnabledForAnyListener = true; @@ -2840,8 +2850,10 @@ internal void DoCommand(EventCommandEventArgs commandArgs) /// of 'eventId. If value is 'false' disable the event for that dispatcher. If 'eventId' is out of /// range return false, otherwise true. /// - internal bool EnableEventForDispatcher(EventDispatcher dispatcher, EventProviderType eventProviderType, int eventId, bool value) + internal bool EnableEventForDispatcher(EventDispatcher? dispatcher, EventProviderType eventProviderType, int eventId, bool value) { + Debug.Assert(m_eventData != null); + if (dispatcher == null) { if (eventId >= m_eventData.Length) @@ -2857,6 +2869,7 @@ internal bool EnableEventForDispatcher(EventDispatcher dispatcher, EventProvider } else { + Debug.Assert(dispatcher.m_EventEnabled != null); if (eventId >= dispatcher.m_EventEnabled.Length) return false; dispatcher.m_EventEnabled[eventId] = value; @@ -2871,6 +2884,8 @@ internal bool EnableEventForDispatcher(EventDispatcher dispatcher, EventProvider /// private bool AnyEventEnabled() { + Debug.Assert(m_eventData != null); + for (int i = 0; i < m_eventData.Length; i++) if (m_eventData[i].EnabledForETW || m_eventData[i].EnabledForAnyListener #if FEATURE_PERFTRACING @@ -2894,9 +2909,9 @@ private void EnsureDescriptorsInitialized() if (m_eventData == null) { Guid eventSourceGuid = Guid.Empty; - string eventSourceName = null; - EventMetadata[] eventData = null; - byte[] manifest = null; + string? eventSourceName = null; + EventMetadata[]? eventData = null; + byte[]? manifest = null; // Try the GetMetadata provided by the ILTransform in ProjectN. The default sets all to null, and in that case we fall back // to the reflection approach. @@ -2909,7 +2924,6 @@ private void EnsureDescriptorsInitialized() m_rawManifest = CreateManifestAndDescriptors(this.GetType(), Name, this); Debug.Assert(m_eventData != null); - } else { @@ -2920,6 +2934,7 @@ private void EnsureDescriptorsInitialized() m_rawManifest = manifest; } // TODO Enforce singleton pattern + Debug.Assert(EventListener.s_EventSources != null, "should be called within lock on EventListener.EventListenersLock which ensures s_EventSources to be initialized"); foreach (WeakReference eventSourceRef in EventListener.s_EventSources) { if (eventSourceRef.Target is EventSource eventSource && eventSource.Guid == m_guid && !eventSource.IsDisposed) @@ -2932,7 +2947,7 @@ private void EnsureDescriptorsInitialized() } // Make certain all dispatchers also have their arrays initialized - EventDispatcher dispatcher = m_Dispatchers; + EventDispatcher? dispatcher = m_Dispatchers; while (dispatcher != null) { if (dispatcher.m_EventEnabled == null) @@ -2956,7 +2971,7 @@ private void EnsureDescriptorsInitialized() // Send out the ETW manifest XML out to ETW // Today, we only send the manifest to ETW, custom listeners don't get it. - private unsafe bool SendManifest(byte[] rawManifest) + private unsafe bool SendManifest(byte[]? rawManifest) { bool success = true; @@ -3041,7 +3056,7 @@ internal static Attribute GetCustomAttributeHelper(Type type, Type attributeType // Helper to deal with the fact that the type we are reflecting over might be loaded in the ReflectionOnly context. // When that is the case, we have the build the custom assemblies on a member by hand. - internal static Attribute GetCustomAttributeHelper(MemberInfo member, Type attributeType, EventManifestOptions flags = EventManifestOptions.None) + internal static Attribute? GetCustomAttributeHelper(MemberInfo member, Type attributeType, EventManifestOptions flags = EventManifestOptions.None) { #if !ES_BUILD_PN // On ProjectN, ReflectionOnly() always equals false. AllowEventSourceOverride is an option that allows either Microsoft.Diagnostics.Tracing or @@ -3050,7 +3065,7 @@ internal static Attribute GetCustomAttributeHelper(MemberInfo member, Type attri #endif // !ES_BUILD_PN { // Let the runtime to the work for us, since we can execute code in this context. - Attribute firstAttribute = null; + Attribute? firstAttribute = null; foreach (var attribute in member.GetCustomAttributes(attributeType, false)) { firstAttribute = (Attribute)attribute; @@ -3061,7 +3076,7 @@ internal static Attribute GetCustomAttributeHelper(MemberInfo member, Type attri #if (!ES_BUILD_PCL && !ES_BUILD_PN) // In the reflection only context, we have to do things by hand. - string fullTypeNameToFind = attributeType.FullName; + string fullTypeNameToFind = attributeType.FullName!; #if EVENT_SOURCE_LEGACY_NAMESPACE_SUPPORT fullTypeNameToFind = fullTypeNameToFind.Replace("System.Diagnostics.Eventing", "System.Diagnostics.Tracing"); @@ -3069,19 +3084,19 @@ internal static Attribute GetCustomAttributeHelper(MemberInfo member, Type attri foreach (CustomAttributeData data in CustomAttributeData.GetCustomAttributes(member)) { - if (AttributeTypeNamesMatch(attributeType, data.Constructor.ReflectedType)) + if (AttributeTypeNamesMatch(attributeType, data.Constructor.ReflectedType!)) { - Attribute attr = null; + Attribute? attr = null; Debug.Assert(data.ConstructorArguments.Count <= 1); if (data.ConstructorArguments.Count == 1) { - attr = (Attribute)Activator.CreateInstance(attributeType, new object[] { data.ConstructorArguments[0].Value }); + attr = (Attribute?)Activator.CreateInstance(attributeType, new object?[] { data.ConstructorArguments[0].Value }); } else if (data.ConstructorArguments.Count == 0) { - attr = (Attribute)Activator.CreateInstance(attributeType); + attr = (Attribute?)Activator.CreateInstance(attributeType); } if (attr != null) @@ -3090,12 +3105,13 @@ internal static Attribute GetCustomAttributeHelper(MemberInfo member, Type attri foreach (CustomAttributeNamedArgument namedArgument in data.NamedArguments) { - PropertyInfo p = t.GetProperty(namedArgument.MemberInfo.Name, BindingFlags.Public | BindingFlags.Instance); - object value = namedArgument.TypedValue.Value; + PropertyInfo p = t.GetProperty(namedArgument.MemberInfo.Name, BindingFlags.Public | BindingFlags.Instance)!; + object value = namedArgument.TypedValue.Value!; if (p.PropertyType.IsEnum) { - value = Enum.Parse(p.PropertyType, value.ToString()); + string val = value.ToString()!; + value = Enum.Parse(p.PropertyType, val); } p.SetValue(attr, value, null); @@ -3132,73 +3148,68 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt // are the typenames equal and the namespaces under "Diagnostics.Tracing" (typically // either Microsoft.Diagnostics.Tracing or System.Diagnostics.Tracing)? string.Equals(attributeType.Name, reflectedAttributeType.Name, StringComparison.Ordinal) && - attributeType.Namespace.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) && - (reflectedAttributeType.Namespace.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) + attributeType.Namespace!.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) && + (reflectedAttributeType.Namespace!.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) #if EVENT_SOURCE_LEGACY_NAMESPACE_SUPPORT || reflectedAttributeType.Namespace.EndsWith("Diagnostics.Eventing", StringComparison.Ordinal) #endif ); } - private static Type GetEventSourceBaseType(Type eventSourceType, bool allowEventSourceOverride, bool reflectionOnly) + private static Type? GetEventSourceBaseType(Type eventSourceType, bool allowEventSourceOverride, bool reflectionOnly) { + Type? ret = eventSourceType; + // return false for "object" and interfaces - if (eventSourceType.BaseType() == null) + if (ret.BaseType() == null) return null; // now go up the inheritance chain until hitting a concrete type ("object" at worse) do { - eventSourceType = eventSourceType.BaseType(); + ret = ret.BaseType(); } - while (eventSourceType != null && eventSourceType.IsAbstract()); + while (ret != null && ret.IsAbstract()); - if (eventSourceType != null) + if (ret != null) { if (!allowEventSourceOverride) { - if (reflectionOnly && eventSourceType.FullName != typeof(EventSource).FullName || - !reflectionOnly && eventSourceType != typeof(EventSource)) + if (reflectionOnly && ret.FullName != typeof(EventSource).FullName || + !reflectionOnly && ret != typeof(EventSource)) return null; } else { - if (eventSourceType.Name != "EventSource") + if (ret.Name != "EventSource") return null; } } - return eventSourceType; + return ret; } // Use reflection to look at the attributes of a class, and generate a manifest for it (as UTF8) and // return the UTF8 bytes. It also sets up the code:EventData structures needed to dispatch events // at run time. 'source' is the event source to place the descriptors. If it is null, // then the descriptors are not creaed, and just the manifest is generated. - private static byte[] CreateManifestAndDescriptors(Type eventSourceType, string eventSourceDllName, EventSource source, + private static byte[]? CreateManifestAndDescriptors(Type eventSourceType, string? eventSourceDllName, EventSource? source, EventManifestOptions flags = EventManifestOptions.None) { - ManifestBuilder manifest = null; + ManifestBuilder? manifest = null; bool bNeedsManifest = source != null ? !source.SelfDescribingEvents : true; - Exception exception = null; // exception that might get raised during validation b/c we couldn't/didn't recover from a previous error - byte[] res = null; + Exception? exception = null; // exception that might get raised during validation b/c we couldn't/didn't recover from a previous error + byte[]? res = null; if (eventSourceType.IsAbstract() && (flags & EventManifestOptions.Strict) == 0) return null; -#if DEBUG && ES_BUILD_STANDALONE && TEST_SUPPORT - TestSupport.TestHooks.MaybeThrow(eventSourceType, - TestSupport.Category.ManifestError, - "EventSource_CreateManifestAndDescriptors", - new ArgumentException("EventSource_CreateManifestAndDescriptors")); -#endif - try { MethodInfo[] methods = eventSourceType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); EventAttribute defaultEventAttribute; int eventId = 1; // The number given to an event that does not have a explicitly given ID. - EventMetadata[] eventData = null; - Dictionary eventsByName = null; + EventMetadata[]? eventData = null; + Dictionary? eventsByName = null; if (source != null || (flags & EventManifestOptions.Strict) != 0) { eventData = new EventMetadata[methods.Length + 1]; @@ -3206,8 +3217,8 @@ private static byte[] CreateManifestAndDescriptors(Type eventSourceType, string } // See if we have localization information. - ResourceManager resources = null; - EventSourceAttribute eventSourceAttrib = (EventSourceAttribute)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags); + ResourceManager? resources = null; + EventSourceAttribute? eventSourceAttrib = (EventSourceAttribute?)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags); if (eventSourceAttrib != null && eventSourceAttrib.LocalizationResources != null) resources = new ResourceManager(eventSourceAttrib.LocalizationResources, eventSourceType.Assembly()); @@ -3241,7 +3252,7 @@ private static byte[] CreateManifestAndDescriptors(Type eventSourceType, string foreach (var providerEnumKind in new string[] { "Keywords", "Tasks", "Opcodes" }) #endif { - Type nestedType = eventSourceType.GetNestedType(providerEnumKind); + Type? nestedType = eventSourceType.GetNestedType(providerEnumKind); if (nestedType != null) { if (eventSourceType.IsAbstract()) @@ -3273,7 +3284,7 @@ private static byte[] CreateManifestAndDescriptors(Type eventSourceType, string ParameterInfo[] args = method.GetParameters(); // Get the EventDescriptor (from the Custom attributes) - EventAttribute eventAttribute = (EventAttribute)GetCustomAttributeHelper(method, typeof(EventAttribute), flags); + EventAttribute? eventAttribute = (EventAttribute?)GetCustomAttributeHelper(method, typeof(EventAttribute), flags); // Compat: until v4.5.1 we ignored any non-void returning methods as well as virtual methods for // the only reason of limiting the number of methods considered to be events. This broke a common @@ -3391,13 +3402,14 @@ private static byte[] CreateManifestAndDescriptors(Type eventSourceType, string manifest.StartEvent(eventName, eventAttribute); for (int fieldIdx = 0; fieldIdx < args.Length; fieldIdx++) { - manifest.AddEventParameter(args[fieldIdx].ParameterType, args[fieldIdx].Name); + manifest.AddEventParameter(args[fieldIdx].ParameterType, args[fieldIdx].Name!); } manifest.EndEvent(); } if (source != null || (flags & EventManifestOptions.Strict) != 0) { + Debug.Assert(eventData != null); // Do checking for user errors (optional, but not a big deal so we do it). DebugCheckEvent(ref eventsByName, eventData, method, eventAttribute, manifest, flags); @@ -3413,11 +3425,11 @@ private static byte[] CreateManifestAndDescriptors(Type eventSourceType, string } #endif string eventKey = "event_" + eventName; - string msg = manifest.GetLocalizedMessage(eventKey, CultureInfo.CurrentUICulture, etwFormat: false); + string? msg = manifest.GetLocalizedMessage(eventKey, CultureInfo.CurrentUICulture, etwFormat: false); // overwrite inline message with the localized message if (msg != null) eventAttribute.Message = msg; - AddEventDescriptor(ref eventData, eventName, eventAttribute, args, hasRelatedActivityID); + AddEventDescriptor(ref eventData!, eventName, eventAttribute, args, hasRelatedActivityID); // TODO-NULLABLE: Remove ! when nullable attributes are respected } } } @@ -3427,7 +3439,8 @@ private static byte[] CreateManifestAndDescriptors(Type eventSourceType, string if (source != null) { - TrimEventDescriptors(ref eventData); + Debug.Assert(eventData != null); + TrimEventDescriptors(ref eventData!); // TODO-NULLABLE: Pass non-null string? to string ref (https://github.com/dotnet/roslyn/issues/34874) source.m_eventData = eventData; // officially initialize it. We do this at most once (it is racy otherwise). #if FEATURE_MANAGED_ETW_CHANNELS source.m_channelData = manifest.GetChannelData(); @@ -3459,10 +3472,11 @@ private static byte[] CreateManifestAndDescriptors(Type eventSourceType, string exception = e; } - if ((flags & EventManifestOptions.Strict) != 0 && (manifest.Errors.Count > 0 || exception != null)) + if ((flags & EventManifestOptions.Strict) != 0 && (manifest?.Errors.Count > 0 || exception != null)) { string msg = string.Empty; - if (manifest.Errors.Count > 0) + + if (manifest?.Errors.Count > 0) { bool firstError = true; foreach (string error in manifest.Errors) @@ -3474,7 +3488,7 @@ private static byte[] CreateManifestAndDescriptors(Type eventSourceType, string } } else - msg = "Unexpected error: " + exception.Message; + msg = "Unexpected error: " + exception!.Message; throw new ArgumentException(msg, exception); } @@ -3538,11 +3552,14 @@ private static void AddProviderEnumKind(ManifestBuilder manifest, FieldInfo stat // Helper used by code:CreateManifestAndDescriptors to add a code:EventData descriptor for a method // with the code:EventAttribute 'eventAttribute'. resourceManger may be null in which case we populate it // it is populated if we need to look up message resources - private static void AddEventDescriptor(ref EventMetadata[] eventData, string eventName, - EventAttribute eventAttribute, ParameterInfo[] eventParameters, - bool hasRelatedActivityID) + private static void AddEventDescriptor( + [NotNull] ref EventMetadata[] eventData, + string eventName, + EventAttribute eventAttribute, + ParameterInfo[] eventParameters, + bool hasRelatedActivityID) { - if (eventData == null || eventData.Length <= eventAttribute.EventId) + if (eventData.Length <= eventAttribute.EventId) { EventMetadata[] newValues = new EventMetadata[Math.Max(eventData.Length + 16, eventAttribute.EventId + 1)]; Array.Copy(eventData, 0, newValues, 0, eventData.Length); @@ -3596,7 +3613,7 @@ internal void AddListener(EventListener listener) { lock (EventListener.EventListenersLock) { - bool[] enabledArray = null; + bool[]? enabledArray = null; if (m_eventData != null) enabledArray = new bool[m_eventData.Length]; m_Dispatchers = new EventDispatcher(m_Dispatchers, enabledArray, listener); @@ -3606,7 +3623,7 @@ internal void AddListener(EventListener listener) // Helper used by code:CreateManifestAndDescriptors to find user mistakes like reusing an event // index for two distinct events etc. Throws exceptions when it finds something wrong. - private static void DebugCheckEvent(ref Dictionary eventsByName, + private static void DebugCheckEvent(ref Dictionary? eventsByName, EventMetadata[] eventData, MethodInfo method, EventAttribute eventAttribute, ManifestBuilder manifest, EventManifestOptions options) { @@ -3713,7 +3730,7 @@ private static int GetHelperCallFirstArg(MethodInfo method) #if ES_BUILD_STANDALONE (new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)).Assert(); #endif - byte[] instrs = method.GetMethodBody().GetILAsByteArray(); + byte[] instrs = method.GetMethodBody().GetILAsByteArray()!; int retVal = -1; for (int idx = 0; idx < instrs.Length;) { @@ -3912,13 +3929,13 @@ private bool SelfDescribingEvents } // private instance state - private string m_name; // My friendly name (privided in ctor) + private string m_name = null!; // My friendly name (privided in ctor) internal int m_id; // A small integer that is unique to this instance. private Guid m_guid; // GUID representing the ETW eventSource to the OS. - internal volatile EventMetadata[] m_eventData; // None per-event data - private volatile byte[] m_rawManifest; // Bytes to send out representing the event schema + internal volatile EventMetadata[]? m_eventData; // None per-event data + private volatile byte[]? m_rawManifest; // Bytes to send out representing the event schema - private EventHandler m_eventCommandExecuted; + private EventHandler? m_eventCommandExecuted; private EventSourceSettings m_config; // configuration information @@ -3930,19 +3947,19 @@ private bool SelfDescribingEvents internal EventKeywords m_matchAnyKeyword; // the logical OR of all levels enabled by any output dispatcher (zero is a special case) meaning 'all keywords' // Dispatching state - internal volatile EventDispatcher m_Dispatchers; // Linked list of code:EventDispatchers we write the data to (we also do ETW specially) + internal volatile EventDispatcher? m_Dispatchers; // Linked list of code:EventDispatchers we write the data to (we also do ETW specially) #if FEATURE_MANAGED_ETW - private volatile OverideEventProvider m_etwProvider; // This hooks up ETW commands to our 'OnEventCommand' callback + private volatile OverideEventProvider m_etwProvider = null!; // This hooks up ETW commands to our 'OnEventCommand' callback #endif #if FEATURE_PERFTRACING - private volatile OverideEventProvider m_eventPipeProvider; + private volatile OverideEventProvider m_eventPipeProvider = null!; #endif private bool m_completelyInited; // The EventSource constructor has returned without exception. - private Exception m_constructionException; // If there was an exception construction, this is it + private Exception? m_constructionException; // If there was an exception construction, this is it private byte m_outOfBandMessageCount; // The number of out of band messages sent (we throttle them - private EventCommandEventArgs m_deferredCommands;// If we get commands before we are fully we store them here and run the when we are fully inited. + private EventCommandEventArgs? m_deferredCommands;// If we get commands before we are fully we store them here and run the when we are fully inited. - private string[] m_traits; // Used to implement GetTraits + private string[]? m_traits; // Used to implement GetTraits internal static uint s_currentPid; // current process id, used in synthesizing quasi-GUIDs [ThreadStatic] @@ -3952,12 +3969,12 @@ private bool SelfDescribingEvents private static bool m_EventSourceInDecodeObject = false; #if FEATURE_MANAGED_ETW_CHANNELS - internal volatile ulong[] m_channelData; + internal volatile ulong[]? m_channelData; #endif // We use a single instance of ActivityTracker for all EventSources instances to allow correlation between multiple event providers. // We have m_activityTracker field simply because instance field is more efficient than static field fetch. - ActivityTracker m_activityTracker; + ActivityTracker m_activityTracker = null!; internal const string s_ActivityStartSuffix = "Start"; internal const string s_ActivityStopSuffix = "Stop"; @@ -4041,7 +4058,7 @@ public enum EventSourceSettings /// public class EventListener : IDisposable { - private event EventHandler _EventSourceCreated; + private event EventHandler? _EventSourceCreated; /// /// This event is raised whenever a new eventSource is 'attached' to the dispatcher. @@ -4061,11 +4078,11 @@ public event EventHandler EventSourceCreated { CallBackForExistingEventSources(false, value); - this._EventSourceCreated = (EventHandler)Delegate.Combine(_EventSourceCreated, value); + this._EventSourceCreated = (EventHandler?)Delegate.Combine(_EventSourceCreated, value); } remove { - this._EventSourceCreated = (EventHandler)Delegate.Remove(_EventSourceCreated, value); + this._EventSourceCreated = (EventHandler?)Delegate.Remove(_EventSourceCreated, value); } } @@ -4092,7 +4109,10 @@ static EventListener() public EventListener() { // This will cause the OnEventSourceCreated callback to fire. - CallBackForExistingEventSources(true, (obj, args) => args.EventSource.AddListener((EventListener)obj)); + CallBackForExistingEventSources(true, (obj, args) => + { + args.EventSource!.AddListener((EventListener)obj!); + }); } /// @@ -4122,7 +4142,7 @@ public virtual void Dispose() EventListener prev = s_Listeners; for (;;) { - EventListener cur = prev.m_Next; + EventListener? cur = prev.m_Next; if (cur == null) break; if (cur == this) @@ -4183,7 +4203,7 @@ public void EnableEvents(EventSource eventSource, EventLevel level, EventKeyword /// /// This call never has an effect on other EventListeners. /// - public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword, IDictionary arguments) + public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword, IDictionary? arguments) { if (eventSource == null) { @@ -4245,7 +4265,7 @@ public void DisableEvents(EventSource eventSource) /// internal protected virtual void OnEventSourceCreated(EventSource eventSource) { - EventHandler callBack = this._EventSourceCreated; + EventHandler? callBack = this._EventSourceCreated; if (callBack != null) { EventSourceCreatedEventArgs args = new EventSourceCreatedEventArgs(); @@ -4335,7 +4355,7 @@ internal static void AddEventSource(EventSource newEventSource) { #endif // Add every existing dispatcher to the new EventSource - for (EventListener listener = s_Listeners; listener != null; listener = listener.m_Next) + for (EventListener? listener = s_Listeners; listener != null; listener = listener.m_Next) newEventSource.AddListener(listener); #if DEBUG } @@ -4356,10 +4376,11 @@ internal static void AddEventSource(EventSource newEventSource) // such callbacks on process shutdown or appdomain so that unmanaged code will never // do this. This is what this callback is for. // See bug 724140 for more - private static void DisposeOnShutdown(object sender, EventArgs e) + private static void DisposeOnShutdown(object? sender, EventArgs e) { lock (EventListenersLock) { + Debug.Assert(s_EventSources != null); foreach (var esRef in s_EventSources) { if (esRef.Target is EventSource es) @@ -4380,20 +4401,22 @@ private static void RemoveReferencesToListenerInEventSources(EventListener liste Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif // Foreach existing EventSource in the appdomain + Debug.Assert(s_EventSources != null); foreach (WeakReference eventSourceRef in s_EventSources) { if (eventSourceRef.Target is EventSource eventSource) { + Debug.Assert(eventSource.m_Dispatchers != null); // Is the first output dispatcher the dispatcher we are removing? if (eventSource.m_Dispatchers.m_Listener == listenerToRemove) eventSource.m_Dispatchers = eventSource.m_Dispatchers.m_Next; else { // Remove 'listenerToRemove' from the eventSource.m_Dispatchers linked list. - EventDispatcher prev = eventSource.m_Dispatchers; + EventDispatcher? prev = eventSource.m_Dispatchers; for (;;) { - EventDispatcher cur = prev.m_Next; + EventDispatcher? cur = prev.m_Next; if (cur == null) { Debug.Fail("EventSource did not have a registered EventListener!"); @@ -4432,9 +4455,10 @@ internal static void Validate() lock (EventListenersLock) { + Debug.Assert(s_EventSources != null); // Get all listeners Dictionary allListeners = new Dictionary(); - EventListener cur = s_Listeners; + EventListener? cur = s_Listeners; while (cur != null) { allListeners.Add(cur, true); @@ -4451,7 +4475,7 @@ internal static void Validate() Debug.Assert(eventSource.m_id == id, "Unexpected event source ID."); // None listeners on eventSources exist in the dispatcher list. - EventDispatcher dispatcher = eventSource.m_Dispatchers; + EventDispatcher? dispatcher = eventSource.m_Dispatchers; while (dispatcher != null) { Debug.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list."); @@ -4485,7 +4509,7 @@ internal static object EventListenersLock { if (s_EventSources == null) Interlocked.CompareExchange(ref s_EventSources, new List(2), null); - return s_EventSources; + return s_EventSources!; // TODO-NULLABLE: Remove ! when compiler specially-recognizes CompareExchange for nullability } } @@ -4493,6 +4517,8 @@ private void CallBackForExistingEventSources(bool addToListenersList, EventHandl { lock (EventListenersLock) { + Debug.Assert(s_EventSources != null); + // Disallow creating EventListener reentrancy. if (s_CreatingListener) { @@ -4552,7 +4578,7 @@ private void CallBackForExistingEventSources(bool addToListenersList, EventHandl } // Instance fields - internal volatile EventListener m_Next; // These form a linked list in s_Listeners + internal volatile EventListener? m_Next; // These form a linked list in s_Listeners // static fields @@ -4560,14 +4586,14 @@ private void CallBackForExistingEventSources(bool addToListenersList, EventHandl /// The list of all listeners in the appdomain. Listeners must be explicitly disposed to remove themselves /// from this list. Note that EventSources point to their listener but NOT the reverse. /// - internal static EventListener s_Listeners; + internal static EventListener? s_Listeners; /// /// The list of all active eventSources in the appdomain. Note that eventSources do NOT /// remove themselves from this list this is a weak list and the GC that removes them may /// not have happened yet. Thus it can contain event sources that are dead (thus you have /// to filter those out. /// - internal static List s_EventSources; + internal static List? s_EventSources; /// /// Used to disallow reentrancy. @@ -4604,7 +4630,7 @@ public class EventCommandEventArgs : EventArgs /// /// Gets the arguments for the callback. /// - public IDictionary Arguments { get; internal set; } + public IDictionary? Arguments { get; internal set; } /// /// Enables the event that has the specified identifier. @@ -4632,8 +4658,8 @@ public bool DisableEvent(int eventId) #region private - internal EventCommandEventArgs(EventCommand command, IDictionary arguments, EventSource eventSource, - EventListener listener, EventProviderType eventProviderType, int perEventSourceSessionId, int etwSessionId, bool enable, EventLevel level, EventKeywords matchAnyKeyword) + internal EventCommandEventArgs(EventCommand command, IDictionary? arguments, EventSource eventSource, + EventListener? listener, EventProviderType eventProviderType, int perEventSourceSessionId, int etwSessionId, bool enable, EventLevel level, EventKeywords matchAnyKeyword) { this.Command = command; this.Arguments = arguments; @@ -4648,17 +4674,17 @@ internal EventCommandEventArgs(EventCommand command, IDictionary } internal EventSource eventSource; - internal EventDispatcher dispatcher; + internal EventDispatcher? dispatcher; internal EventProviderType eventProviderType; // These are the arguments of sendCommand and are only used for deferring commands until after we are fully initialized. - internal EventListener listener; + internal EventListener? listener; internal int perEventSourceSessionId; internal int etwSessionId; internal bool enable; internal EventLevel level; internal EventKeywords matchAnyKeyword; - internal EventCommandEventArgs nextCommand; // We form a linked list of these deferred commands. + internal EventCommandEventArgs? nextCommand; // We form a linked list of these deferred commands. #endregion } @@ -4671,7 +4697,7 @@ public class EventSourceCreatedEventArgs : EventArgs /// /// The EventSource that is attaching to the listener. /// - public EventSource EventSource + public EventSource? EventSource { get; internal set; @@ -4687,7 +4713,7 @@ public class EventWrittenEventArgs : EventArgs /// /// The name of the event. /// - public string EventName + public string? EventName { get { @@ -4696,7 +4722,10 @@ public string EventName return m_eventName; } else + { + Debug.Assert(m_eventSource.m_eventData != null); return m_eventSource.m_eventData[EventId].Name; + } } internal set { @@ -4742,12 +4771,12 @@ public Guid RelatedActivityId /// /// Gets the payload for the event. /// - public ReadOnlyCollection Payload { get; internal set; } + public ReadOnlyCollection? Payload { get; internal set; } /// /// Gets the payload argument names. /// - public ReadOnlyCollection PayloadNames + public ReadOnlyCollection? PayloadNames { get { @@ -4758,10 +4787,12 @@ public ReadOnlyCollection PayloadNames { var names = new List(); + Debug.Assert(m_eventSource.m_eventData != null); foreach (var parameter in m_eventSource.m_eventData[EventId].Parameters) { - names.Add(parameter.Name); + names.Add(parameter.Name!); } + m_payloadNames = new ReadOnlyCollection(names); } @@ -4789,6 +4820,7 @@ public EventKeywords Keywords if (EventId < 0) // TraceLogging convention EventID == -1 return m_keywords; + Debug.Assert(m_eventSource.m_eventData != null); return (EventKeywords)m_eventSource.m_eventData[EventId].Descriptor.Keywords; } } @@ -4802,6 +4834,8 @@ public EventOpcode Opcode { if (EventId <= 0) // TraceLogging convention EventID == -1 return m_opcode; + + Debug.Assert(m_eventSource.m_eventData != null); return (EventOpcode)m_eventSource.m_eventData[EventId].Descriptor.Opcode; } } @@ -4816,6 +4850,7 @@ public EventTask Task if (EventId <= 0) // TraceLogging convention EventID == -1 return EventTask.None; + Debug.Assert(m_eventSource.m_eventData != null); return (EventTask)m_eventSource.m_eventData[EventId].Descriptor.Task; } } @@ -4829,6 +4864,8 @@ public EventTags Tags { if (EventId <= 0) // TraceLogging convention EventID == -1 return m_tags; + + Debug.Assert(m_eventSource.m_eventData != null); return m_eventSource.m_eventData[EventId].Tags; } } @@ -4836,14 +4873,19 @@ public EventTags Tags /// /// Gets the message for the event. If the message has {N} parameters they are NOT substituted. /// - public string Message + public string? Message { get { if (EventId <= 0) // TraceLogging convention EventID == -1 + { return m_message; + } else + { + Debug.Assert(m_eventSource.m_eventData != null); return m_eventSource.m_eventData[EventId].Message; + } } internal set { @@ -4862,6 +4904,8 @@ public EventChannel Channel { if (EventId <= 0) // TraceLogging convention EventID == -1 return EventChannel.None; + + Debug.Assert(m_eventSource.m_eventData != null); return (EventChannel)m_eventSource.m_eventData[EventId].Descriptor.Channel; } } @@ -4876,6 +4920,8 @@ public byte Version { if (EventId <= 0) // TraceLogging convention EventID == -1 return 0; + + Debug.Assert(m_eventSource.m_eventData != null); return m_eventSource.m_eventData[EventId].Descriptor.Version; } } @@ -4889,6 +4935,8 @@ public EventLevel Level { if (EventId <= 0) // TraceLogging convention EventID == -1 return m_level; + + Debug.Assert(m_eventSource.m_eventData != null); return (EventLevel)m_eventSource.m_eventData[EventId].Descriptor.Level; } } @@ -4932,10 +4980,10 @@ internal EventWrittenEventArgs(EventSource eventSource) m_eventSource = eventSource; TimeStamp = DateTime.UtcNow; } - private string m_message; - private string m_eventName; + private string? m_message; + private string? m_eventName; private EventSource m_eventSource; - private ReadOnlyCollection m_payloadNames; + private ReadOnlyCollection? m_payloadNames; private Guid m_activityId; private long? m_osThreadId; internal EventTags m_tags; @@ -4954,13 +5002,13 @@ public sealed class EventSourceAttribute : Attribute /// /// Overrides the ETW name of the event source (which defaults to the class name) /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Overrides the default (calculated) Guid of an EventSource type. Explicitly defining a GUID is discouraged, /// except when upgrading existing ETW providers to using event sources. /// - public string Guid { get; set; } + public string? Guid { get; set; } /// /// @@ -4983,7 +5031,7 @@ public sealed class EventSourceAttribute : Attribute /// which represent the payload values. /// /// - public string LocalizationResources { get; set; } + public string? LocalizationResources { get; set; } } /// @@ -5041,7 +5089,7 @@ internal bool IsOpcodeSet /// use standard .NET substitution operators (eg {1}) in the string and they will be replaced /// with the 'ToString()' of the corresponding part of the event payload. /// - public string Message { get; set; } + public string? Message { get; set; } /// /// User defined options associated with the event. These do not have meaning to the EventSource but @@ -5116,12 +5164,12 @@ class EventChannelAttribute : Attribute /// Specifies an SDDL access descriptor that controls access to the log file that backs the channel. /// See MSDN (https://docs.microsoft.com/en-us/windows/desktop/WES/eventmanifestschema-channeltype-complextype) for details. /// - public string Access { get; set; } + public string? Access { get; set; } /// /// Allows importing channels defined in external manifests /// - public string ImportChannel { get; set; } + public string? ImportChannel { get; set; } #endif // TODO: there is a convention that the name is the Provider/Type Should we provide an override? @@ -5302,7 +5350,7 @@ public static explicit operator uint(SessionMask m) /// internal class EventDispatcher { - internal EventDispatcher(EventDispatcher next, bool[] eventEnabled, EventListener listener) + internal EventDispatcher(EventDispatcher? next, bool[]? eventEnabled, EventListener listener) { m_Next = next; m_EventEnabled = eventEnabled; @@ -5311,10 +5359,10 @@ internal EventDispatcher(EventDispatcher next, bool[] eventEnabled, EventListene // Instance fields readonly internal EventListener m_Listener; // The dispatcher this entry is for - internal bool[] m_EventEnabled; // For every event in a the eventSource, is it enabled? + internal bool[]? m_EventEnabled; // For every event in a the eventSource, is it enabled? // Only guaranteed to exist after a InsureInit() - internal EventDispatcher m_Next; // These form a linked list in code:EventSource.m_Dispatchers + internal EventDispatcher? m_Next; // These form a linked list in code:EventSource.m_Dispatchers // Of all listeners for that eventSource. } @@ -5360,7 +5408,7 @@ internal class ManifestBuilder /// Build a manifest for 'providerName' with the given GUID, which will be packaged into 'dllName'. /// 'resources, is a resource manager. If specified all messages are localized using that manager. /// - public ManifestBuilder(string providerName, Guid providerGuid, string dllName, ResourceManager resources, + public ManifestBuilder(string providerName, Guid providerGuid, string? dllName, ResourceManager? resources, EventManifestOptions flags) { #if FEATURE_MANAGED_ETW_CHANNELS @@ -5451,7 +5499,7 @@ public void AddKeyword(string name, ulong value) /// /// Add a channel. channelAttribute can be null /// - public void AddChannel(string name, int value, EventChannelAttribute channelAttribute) + public void AddChannel(string? name, int value, EventChannelAttribute? channelAttribute) { EventChannel chValue = (EventChannel)value; if (value < (int)EventChannel.Admin || value > 255) @@ -5590,6 +5638,8 @@ public void AddEventParameter(Type type, string name) } public void EndEvent() { + Debug.Assert(eventName != null); + if (numParams > 0) { templates.Append(" ").AppendLine(); @@ -5605,7 +5655,7 @@ public void EndEvent() string msg; if (stringTab.TryGetValue("event_" + eventName, out msg)) { - msg = TranslateToManifestConvention(msg, eventName); + msg = TranslateToManifestConvention(msg!, eventName); // https://github.com/dotnet/roslyn/issues/26761 stringTab["event_" + eventName] = msg; } @@ -5695,13 +5745,13 @@ private string CreateManifestString() int channel = kvpair.Key; ChannelInfo channelInfo = kvpair.Value; - string channelType = null; + string? channelType = null; string elementName = "channel"; bool enabled = false; - string fullName = null; + string? fullName = null; #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS - string isolation = null; - string access = null; + string? isolation = null; + string? access = null; #endif if (channelInfo.Attribs != null) { @@ -5728,6 +5778,7 @@ private string CreateManifestString() sb.Append(" name=\"").Append(fullName).Append("\""); if (elementName == "channel") // not applicable to importChannels. { + Debug.Assert(channelInfo.Name != null); WriteMessageAttrib(sb, "channel", channelInfo.Name, null); sb.Append(" value=\"").Append(channel).Append("\""); if (channelType != null) @@ -5862,7 +5913,7 @@ private string CreateManifestString() // Output the localization information. sb.Append("").AppendLine(); - List cultures = null; + List? cultures = null; if (resources != null && (flags & EventManifestOptions.AllCultures) != 0) { cultures = GetSupportedCultures(resources); @@ -5884,7 +5935,7 @@ private string CreateManifestString() foreach (var stringKey in sortedStrings) { - string val = GetLocalizedMessage(stringKey, ci, etwFormat: true); + string? val = GetLocalizedMessage(stringKey, ci, etwFormat: true); sb.Append(" ").AppendLine(); } sb.Append(" ").AppendLine(); @@ -5901,14 +5952,14 @@ private void WriteNameAndMessageAttribs(StringBuilder stringBuilder, string elem stringBuilder.Append(" name=\"").Append(name).Append("\""); WriteMessageAttrib(sb, elementName, name, name); } - private void WriteMessageAttrib(StringBuilder stringBuilder, string elementName, string name, string value) + private void WriteMessageAttrib(StringBuilder stringBuilder, string elementName, string name, string? value) { string key = elementName + "_" + name; // See if the user wants things localized. if (resources != null) { // resource fallback: strings in the neutral culture will take precedence over inline strings - string localizedString = resources.GetString(key, CultureInfo.InvariantCulture); + string? localizedString = resources.GetString(key, CultureInfo.InvariantCulture); if (localizedString != null) value = localizedString; } @@ -5925,12 +5976,12 @@ private void WriteMessageAttrib(StringBuilder stringBuilder, string elementName, stringTab[key] = value; } - internal string GetLocalizedMessage(string key, CultureInfo ci, bool etwFormat) + internal string? GetLocalizedMessage(string key, CultureInfo ci, bool etwFormat) { - string value = null; + string? value = null; if (resources != null) { - string localizedString = resources.GetString(key, ci); + string? localizedString = resources.GetString(key, ci); if (localizedString != null) { value = localizedString; @@ -5969,9 +6020,9 @@ private static string GetLevelName(EventLevel level) } #if FEATURE_MANAGED_ETW_CHANNELS - private string GetChannelName(EventChannel channel, string eventName, string eventMessage) + private string? GetChannelName(EventChannel channel, string eventName, string? eventMessage) { - ChannelInfo info = null; + ChannelInfo? info = null; if (channelTab == null || !channelTab.TryGetValue((int)channel, out info)) { if (channel < EventChannel.Admin) // || channel > EventChannel.Debug) @@ -5993,6 +6044,8 @@ private string GetChannelName(EventChannel channel, string eventName, string eve // events that specify admin channels *must* have non-null "Message" attributes if (resources != null && eventMessage == null) eventMessage = resources.GetString("event_" + eventName, CultureInfo.InvariantCulture); + + Debug.Assert(info.Attribs != null); if (info.Attribs.EventChannelType == EventChannelType.Admin && eventMessage == null) ManifestError(SR.Format(SR.EventSource_EventWithAdminChannelMustHaveMessage, eventName, info.Name)); return info.Name; @@ -6011,7 +6064,7 @@ private string GetTaskName(EventTask task, string eventName) return ret; } - private string GetOpcodeName(EventOpcode opcode, string eventName) + private string? GetOpcodeName(EventOpcode opcode, string eventName) { switch (opcode) { @@ -6039,12 +6092,13 @@ private string GetOpcodeName(EventOpcode opcode, string eventName) return "win:Receive"; } - string ret; + string? ret; if (opcodeTab == null || !opcodeTab.TryGetValue((int)opcode, out ret)) { ManifestError(SR.Format(SR.EventSource_UndefinedOpcode, opcode, eventName), true); ret = null; } + return ret; } @@ -6061,7 +6115,7 @@ private string GetKeywords(ulong keywords, string eventName) { if ((keywords & bit) != 0) { - string keyword = null; + string? keyword = null; if ((keywordTab == null || !keywordTab.TryGetValue(bit, out keyword)) && (bit >= (ulong)0x1000000000000)) { @@ -6133,7 +6187,7 @@ private string GetTypeName(Type type) } } - private static void UpdateStringBuilder(ref StringBuilder stringBuilder, string eventMessage, int startIndex, int count) + private static void UpdateStringBuilder([NotNull] ref StringBuilder? stringBuilder, string eventMessage, int startIndex, int count) { if (stringBuilder == null) stringBuilder = new StringBuilder(); @@ -6145,7 +6199,7 @@ private static void UpdateStringBuilder(ref StringBuilder stringBuilder, string // .NET conventions. We can't use RegEx for this (we are in mscorlib), so we do it 'by hand' private string TranslateToManifestConvention(string eventMessage, string evtName) { - StringBuilder stringBuilder = null; // We lazily create this + StringBuilder? stringBuilder = null; // We lazily create this int writtenSoFar = 0; int chIdx = -1; for (int i = 0; ;) @@ -6155,14 +6209,14 @@ private string TranslateToManifestConvention(string eventMessage, string evtName if (stringBuilder == null) return eventMessage; UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar); - return stringBuilder.ToString(); + return stringBuilder!.ToString(); // TODO-NULLABLE: Remove ! when nullable attributes are respected } if (eventMessage[i] == '%') { // handle format message escaping character '%' by escaping it UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar); - stringBuilder.Append("%%"); + stringBuilder!.Append("%%"); // TODO-NULLABLE: Remove ! when nullable attributes are respected i++; writtenSoFar = i; } @@ -6171,7 +6225,7 @@ private string TranslateToManifestConvention(string eventMessage, string evtName { // handle C# escaped '{" and '}' UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar); - stringBuilder.Append(eventMessage[i]); + stringBuilder!.Append(eventMessage[i]); // TODO-NULLABLE: Remove ! when nullable attributes are respected i++; i++; writtenSoFar = i; } @@ -6190,7 +6244,7 @@ private string TranslateToManifestConvention(string eventMessage, string evtName i++; UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, leftBracket - writtenSoFar); int manIndex = TranslateIndexToManifestConvention(argNum, evtName); - stringBuilder.Append('%').Append(manIndex); + stringBuilder!.Append('%').Append(manIndex); // TODO-NULLABLE: Remove ! when nullable attributes are respected // An '!' after the insert specifier {n} will be interpreted as a literal. // We'll escape it so that mc.exe does not attempt to consider it the // beginning of a format string. @@ -6210,7 +6264,7 @@ private string TranslateToManifestConvention(string eventMessage, string evtName { UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar); i++; - stringBuilder.Append(s_escapes[chIdx]); + stringBuilder!.Append(s_escapes[chIdx]); // TODO-NULLABLE: Remove ! when nullable attributes are respected writtenSoFar = i; } else @@ -6237,19 +6291,19 @@ private int TranslateIndexToManifestConvention(int idx, string evtName) #if FEATURE_MANAGED_ETW_CHANNELS class ChannelInfo { - public string Name; + public string? Name; public ulong Keywords; - public EventChannelAttribute Attribs; + public EventChannelAttribute? Attribs; } #endif Dictionary opcodeTab; - Dictionary taskTab; + Dictionary? taskTab; #if FEATURE_MANAGED_ETW_CHANNELS - Dictionary channelTab; + Dictionary? channelTab; #endif - Dictionary keywordTab; - Dictionary mapsTab; + Dictionary? keywordTab; + Dictionary? mapsTab; Dictionary stringTab; // Maps unlocalized strings to localized ones @@ -6271,15 +6325,15 @@ class ChannelInfo #if FEATURE_MANAGED_ETW_CHANNELS string providerName; #endif - ResourceManager resources; // Look up localized strings here. + ResourceManager? resources; // Look up localized strings here. EventManifestOptions flags; IList errors; // list of currently encountered errors Dictionary> perEventByteArrayArgIndices; // "event_name" -> List_of_Indices_of_Byte[]_Arg // State we track between StartEvent and EndEvent. - string eventName; // Name of the event currently being processed. + string? eventName; // Name of the event currently being processed. int numParams; // keeps track of the number of args the event has. - List byteArrArgIndices; // keeps track of the index of each byte[] argument + List? byteArrArgIndices; // keeps track of the index of each byte[] argument #endregion } diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventSourceException.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventSourceException.cs index f5f9ba13b1a0..5786b38856bb 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventSourceException.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/EventSourceException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.Serialization; diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/FrameworkEventSource.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/FrameworkEventSource.cs index bbeaa246285b..680110f99cf0 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/FrameworkEventSource.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/FrameworkEventSource.cs @@ -33,7 +33,7 @@ private FrameworkEventSource() : base(new Guid(0x8e9f5090, 0x2d75, 0x4d03, 0x8a, // optimized for common signatures (used by the ThreadTransferSend/Receive events) [NonEvent] - private unsafe void WriteEvent(int eventId, long arg1, int arg2, string arg3, bool arg4, int arg5, int arg6) + private unsafe void WriteEvent(int eventId, long arg1, int arg2, string? arg3, bool arg4, int arg5, int arg6) { if (IsEnabled()) { @@ -66,7 +66,7 @@ private unsafe void WriteEvent(int eventId, long arg1, int arg2, string arg3, bo // optimized for common signatures (used by the ThreadTransferSend/Receive events) [NonEvent] - private unsafe void WriteEvent(int eventId, long arg1, int arg2, string arg3) + private unsafe void WriteEvent(int eventId, long arg1, int arg2, string? arg3) { if (IsEnabled()) { @@ -145,7 +145,7 @@ public unsafe void ThreadTransferSendObj(object id, int kind, string info, bool // 3 - WinRT dispatch operations // info - any additional information user code might consider interesting [Event(151, Level = EventLevel.Informational, Keywords = Keywords.ThreadTransfer, Task = Tasks.ThreadTransfer, Opcode = EventOpcode.Receive)] - public void ThreadTransferReceive(long id, int kind, string info) + public void ThreadTransferReceive(long id, int kind, string? info) { WriteEvent(151, id, kind, info); } @@ -153,7 +153,7 @@ public void ThreadTransferReceive(long id, int kind, string info) // keep track of GC movements in order to correlate the value passed to XyzSend with the // (possibly changed) value passed to XyzReceive [NonEvent] - public unsafe void ThreadTransferReceiveObj(object id, int kind, string info) + public unsafe void ThreadTransferReceiveObj(object id, int kind, string? info) { ThreadTransferReceive((long)*((void**)Unsafe.AsPointer(ref id)), kind, info); } diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/IncrementingEventCounter.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/IncrementingEventCounter.cs index 40581051cc9f..e084bbb1c198 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/IncrementingEventCounter.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/IncrementingEventCounter.cs @@ -43,7 +43,7 @@ public IncrementingEventCounter(string name, EventSource eventSource) : base(nam /// The value to increment by. public void Increment(double increment = 1) { - lock(MyLock) + lock (MyLock) { _increment += increment; } @@ -55,7 +55,7 @@ public void Increment(double increment = 1) public override string ToString() => $"IncrementingEventCounter '{Name}' Increment {_increment}"; - internal override void WritePayload(float intervalSec) + internal override void WritePayload(float intervalSec, int pollingIntervalMillisec) { lock (MyLock) // Lock the counter { @@ -64,6 +64,8 @@ internal override void WritePayload(float intervalSec) payload.IntervalSec = intervalSec; payload.DisplayName = DisplayName ?? ""; payload.DisplayRateTimeScale = (DisplayRateTimeScale == TimeSpan.Zero) ? "" : DisplayRateTimeScale.ToString("c"); + payload.Series = $"Interval={pollingIntervalMillisec}"; // TODO: This may need to change when we support multi-session + payload.CounterType = "Sum"; payload.Metadata = GetMetadataString(); payload.Increment = _increment - _prevIncrement; _prevIncrement = _increment; diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/IncrementingPollingCounter.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/IncrementingPollingCounter.cs index 1b8ee7553e4d..116fbe8290d3 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/IncrementingPollingCounter.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/IncrementingPollingCounter.cs @@ -36,6 +36,9 @@ public partial class IncrementingPollingCounter : DiagnosticCounter /// The event source. public IncrementingPollingCounter(string name, EventSource eventSource, Func totalValueProvider) : base(name, eventSource) { + if (totalValueProvider == null) + throw new ArgumentNullException(nameof(totalValueProvider)); + _totalValueProvider = totalValueProvider; } @@ -53,7 +56,7 @@ private void UpdateMetric() { try { - lock(MyLock) + lock (MyLock) { _increment = _totalValueProvider(); } @@ -64,7 +67,7 @@ private void UpdateMetric() } } - internal override void WritePayload(float intervalSec) + internal override void WritePayload(float intervalSec, int pollingIntervalMillisec) { UpdateMetric(); lock (MyLock) // Lock the counter @@ -74,6 +77,8 @@ internal override void WritePayload(float intervalSec) payload.DisplayName = DisplayName ?? ""; payload.DisplayRateTimeScale = (DisplayRateTimeScale == TimeSpan.Zero) ? "" : DisplayRateTimeScale.ToString("c"); payload.IntervalSec = intervalSec; + payload.Series = $"Interval={pollingIntervalMillisec}"; // TODO: This may need to change when we support multi-session + payload.CounterType = "Sum"; payload.Metadata = GetMetadataString(); payload.Increment = _increment - _prevIncrement; _prevIncrement = _increment; diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/PollingCounter.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/PollingCounter.cs index e0577181facc..abb472cd2ee9 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/PollingCounter.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/PollingCounter.cs @@ -34,6 +34,9 @@ public partial class PollingCounter : DiagnosticCounter /// The event source. public PollingCounter(string name, EventSource eventSource, Func metricProvider) : base(name, eventSource) { + if (metricProvider == null) + throw new ArgumentNullException(nameof(metricProvider)); + _metricProvider = metricProvider; } @@ -42,7 +45,7 @@ public PollingCounter(string name, EventSource eventSource, Func metricP private Func _metricProvider; private double _lastVal; - internal override void WritePayload(float intervalSec) + internal override void WritePayload(float intervalSec, int pollingIntervalMillisec) { lock (MyLock) { @@ -61,6 +64,8 @@ internal override void WritePayload(float intervalSec) payload.DisplayName = DisplayName ?? ""; payload.Count = 1; // NOTE: These dumb-looking statistics is intentional payload.IntervalSec = intervalSec; + payload.Series = $"Interval={pollingIntervalMillisec}"; // TODO: This may need to change when we support multi-session + payload.CounterType = "Mean"; payload.Mean = value; payload.Max = value; payload.Min = value; diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/StubEnvironment.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/StubEnvironment.cs index d376389043be..a719dc6bce73 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/StubEnvironment.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/StubEnvironment.cs @@ -28,24 +28,18 @@ internal static class Environment public static int TickCount { get { return System.Environment.TickCount; } } - public static string GetResourceString(string key, params object[] args) + public static string GetResourceString(string key, params object?[] args) { - string fmt = rm.GetString(key); + string? fmt = rm.GetString(key); if (fmt != null) return string.Format(fmt, args); - string sargs = string.Empty; - foreach(var arg in args) - { - if (sargs != string.Empty) - sargs += ", "; - sargs += arg.ToString(); - } + string sargs = string.Join(", ", args); return key + " (" + sargs + ")"; } - public static string GetRuntimeResourceString(string key, params object[] args) + public static string GetRuntimeResourceString(string key, params object?[] args) { return GetResourceString(key, args); } @@ -226,7 +220,7 @@ static class ReflectionExtensions public static bool IsSealed(this Type type) { return type.IsSealed; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } - public static Type BaseType(this Type type) { return type.BaseType; } + public static Type? BaseType(this Type type) { return type.BaseType; } public static Assembly Assembly(this Type type) { return type.Assembly; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } @@ -242,7 +236,7 @@ static class ReflectionExtensions public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool IsGenericType(this Type type) { return type.IsConstructedGenericType; } - public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; } + public static Type? BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static Assembly Assembly(this Type type) { return type.GetTypeInfo().Assembly; } public static IEnumerable GetProperties(this Type type) { @@ -252,7 +246,7 @@ public static IEnumerable GetProperties(this Type type) return type.GetRuntimeProperties(); #endif } - public static MethodInfo GetGetMethod(this PropertyInfo propInfo) { return propInfo.GetMethod; } + public static MethodInfo? GetGetMethod(this PropertyInfo propInfo) { return propInfo.GetMethod; } public static Type[] GetGenericArguments(this Type type) { return type.GenericTypeArguments; } public static MethodInfo[] GetMethods(this Type type, BindingFlags flags) @@ -313,9 +307,9 @@ public static FieldInfo[] GetFields(this Type type, BindingFlags flags) } return fieldInfos.ToArray(); } - public static Type GetNestedType(this Type type, string nestedTypeName) + public static Type? GetNestedType(this Type type, string nestedTypeName) { - TypeInfo ti = null; + TypeInfo? ti = null; foreach(var nt in type.GetTypeInfo().DeclaredNestedTypes) { if (nt.Name == nestedTypeName) @@ -349,7 +343,7 @@ public static TypeCode GetTypeCode(this Type type) // // FieldInfo extension methods // - public static object GetRawConstantValue(this FieldInfo fi) + public static object? GetRawConstantValue(this FieldInfo fi) { return fi.GetValue(null); } // diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/ArrayTypeInfo.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/ArrayTypeInfo.cs index 5771354f671e..3a607d4b0d99 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/ArrayTypeInfo.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/ArrayTypeInfo.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics; #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing @@ -23,7 +24,7 @@ public ArrayTypeInfo(Type type, TraceLoggingTypeInfo elementInfo) public override void WriteMetadata( TraceLoggingMetadataCollector collector, - string name, + string? name, EventFieldFormat format) { collector.BeginBufferedArray(); @@ -36,7 +37,7 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu var bookmark = collector.BeginBufferedArray(); var count = 0; - Array array = (Array)value.ReferenceValue; + Array? array = (Array?)value.ReferenceValue; if (array != null) { count = array.Length; @@ -49,10 +50,11 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu collector.EndBufferedArray(bookmark, count); } - public override object GetData(object value) + public override object? GetData(object? value) { + Debug.Assert(value != null, "null accepted only for some overrides"); var array = (Array)value; - var serializedArray = new object[array.Length]; + var serializedArray = new object?[array.Length]; for (int i = 0; i < array.Length; i++) { serializedArray[i] = this.elementInfo.GetData(array.GetValue(i)); diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/ConcurrentSet.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/ConcurrentSet.cs index 76c01c6c0683..fca673de58d5 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/ConcurrentSet.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/ConcurrentSet.cs @@ -26,11 +26,11 @@ namespace System.Diagnostics.Tracing internal struct ConcurrentSet where ItemType : ConcurrentSetItem { - private ItemType[] items; + private ItemType[]? items; - public ItemType TryGet(KeyType key) + public ItemType? TryGet(KeyType key) { - ItemType item; + ItemType? item; var oldItems = this.items; if (oldItems != null) @@ -110,7 +110,7 @@ public ItemType GetOrAdd(ItemType newItem) Array.Copy(oldItems, lo, newItems, lo + 1, oldLength - lo); } - newItems = Interlocked.CompareExchange(ref this.items, newItems, oldItems); + newItems = Interlocked.CompareExchange(ref this.items, newItems, oldItems)!; if (oldItems != newItems) { oldItems = newItems; diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs index 11c18a260f9e..aa60ac8d0540 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.Resources; using System.Runtime.InteropServices; using System.Security; @@ -35,7 +36,7 @@ internal unsafe struct DataCollector private byte* scratch; private EventSource.EventData* datas; private GCHandle* pins; - private byte[] buffer; + private byte[]? buffer; private int bufferPos; private int bufferNesting; // We may merge many fields int a single blob. If we are doing this we increment this. private bool writingScalars; @@ -102,6 +103,8 @@ internal void AddScalar(void* value, int size) var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); + Debug.Assert(buffer != null); + for (int i = 0; i != size; i++, oldPos++) { this.buffer[oldPos] = pb[i]; @@ -109,7 +112,7 @@ internal void AddScalar(void* value, int size) } } - internal void AddBinary(string value, int size) + internal void AddBinary(string? value, int size) { if (size > ushort.MaxValue) { @@ -135,6 +138,8 @@ internal void AddBinary(string value, int size) var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); + Debug.Assert(buffer != null); + fixed (void* p = value) { Marshal.Copy((IntPtr)p, buffer, oldPos, size); @@ -143,7 +148,7 @@ internal void AddBinary(string value, int size) } } - internal unsafe void AddNullTerminatedString(string value) + internal unsafe void AddNullTerminatedString(string? value) { // Treat null strings as empty strings. if (value == null) @@ -175,6 +180,8 @@ internal unsafe void AddNullTerminatedString(string value) var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); + Debug.Assert(buffer != null); + fixed (void* p = value) { Marshal.Copy((IntPtr)p, buffer, oldPos, size); @@ -187,7 +194,7 @@ internal void AddBinary(Array value, int size) this.AddArray(value, size, 1); } - internal void AddArray(Array value, int length, int itemSize) + internal void AddArray(Array? value, int length, int itemSize) { if (length > ushort.MaxValue) { @@ -214,6 +221,7 @@ internal void AddArray(Array value, int length, int itemSize) var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); + Debug.Assert(value != null && buffer != null); Buffer.BlockCopy(value, 0, this.buffer, oldPos, size); } } @@ -238,6 +246,7 @@ internal int BeginBufferedArray() internal void EndBufferedArray(int bookmark, int count) { this.EnsureBuffer(); + Debug.Assert(buffer != null); this.buffer[bookmark - 2] = unchecked((byte)count); this.buffer[bookmark - 1] = unchecked((byte)(count >> 8)); this.EndBuffered(); @@ -270,6 +279,7 @@ more efficient to buffer the array instead of pinning it. */ this.EnsureBuffer(); + Debug.Assert(buffer != null); this.PinArray(this.buffer, this.bufferPos); this.buffer = null; this.bufferPos = 0; @@ -307,7 +317,7 @@ private void GrowBuffer(int required) Array.Resize(ref this.buffer, newSize); } - private void PinArray(object value, int size) + private void PinArray(object? value, int size) { var pinsTemp = this.pins; if (this.pinsEnd <= pinsTemp) diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EnumHelper.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EnumHelper.cs index 7a23378bb166..33c085dcd17e 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EnumHelper.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EnumHelper.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. + #if EVENTSOURCE_GENERICS ?using System; using System.Reflection; diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EnumerableTypeInfo.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EnumerableTypeInfo.cs index 74a3fa27b2ca..c8ebdf8ab4d4 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EnumerableTypeInfo.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EnumerableTypeInfo.cs @@ -5,6 +5,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing @@ -24,7 +25,7 @@ public EnumerableTypeInfo(Type type, TraceLoggingTypeInfo elementInfo) public override void WriteMetadata( TraceLoggingMetadataCollector collector, - string name, + string? name, EventFieldFormat format) { collector.BeginBufferedArray(); @@ -37,7 +38,7 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu var bookmark = collector.BeginBufferedArray(); var count = 0; - IEnumerable enumerable = (IEnumerable)value.ReferenceValue; + IEnumerable? enumerable = (IEnumerable?)value.ReferenceValue; if (enumerable != null) { foreach (var element in enumerable) @@ -50,10 +51,11 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu collector.EndBufferedArray(bookmark, count); } - public override object GetData(object value) + public override object? GetData(object? value) { + Debug.Assert(value != null, "null accepted only for some overrides"); var iterType = (IEnumerable)value; - List serializedEnumerable = new List(); + List serializedEnumerable = new List(); foreach (var element in iterType) { serializedEnumerable.Add(elementInfo.GetData(element)); diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventDataAttribute.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventDataAttribute.cs index cdedf13c6417..bcfd34515f8a 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventDataAttribute.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventDataAttribute.cs @@ -53,7 +53,7 @@ public class EventDataAttribute /// else /// fieldName = typeof(T).Name; /// - public string Name + public string? Name { get; set; diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventFieldAttribute.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventFieldAttribute.cs index 1a298c285138..b3e4be4a7e43 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventFieldAttribute.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventFieldAttribute.cs @@ -58,7 +58,7 @@ public EventFieldTags Tags /// as the event field's name. /// TODO REMOVE /// - internal string Name + internal string? Name { get; set; diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs index 22abdbef1957..3572352111ca 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs @@ -3,9 +3,10 @@ // See the LICENSE file in the project root for more information. using System; -using System.Collections.Generic; using System.Collections; +using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; @@ -24,9 +25,9 @@ namespace System.Diagnostics.Tracing /// EventSource APIs. /// Preserving the order of the elements as they were found inside user defined types is the most important characteristic of this class. /// - internal class EventPayload : IDictionary + internal class EventPayload : IDictionary { - internal EventPayload(List payloadNames, List payloadValues) + internal EventPayload(List payloadNames, List payloadValues) { Debug.Assert(payloadNames.Count == payloadValues.Count); @@ -35,9 +36,9 @@ internal EventPayload(List payloadNames, List payloadValues) } public ICollection Keys { get { return m_names; } } - public ICollection Values { get { return m_values; } } + public ICollection Values { get { return m_values; } } - public object this[string key] + public object? this[string key] { get { @@ -62,12 +63,12 @@ public object this[string key] } } - public void Add(string key, object value) + public void Add(string key, object? value) { throw new System.NotSupportedException(); } - public void Add(KeyValuePair payloadEntry) + public void Add(KeyValuePair payloadEntry) { throw new System.NotSupportedException(); } @@ -77,7 +78,7 @@ public void Clear() throw new System.NotSupportedException(); } - public bool Contains(KeyValuePair entry) + public bool Contains(KeyValuePair entry) { return ContainsKey(entry.Key); } @@ -99,21 +100,21 @@ public bool ContainsKey(string key) public bool IsReadOnly { get { return true; } } - public IEnumerator> GetEnumerator() + public IEnumerator> GetEnumerator() { for (int i = 0; i < Keys.Count; i++) { - yield return new KeyValuePair(this.m_names[i], this.m_values[i]); + yield return new KeyValuePair(this.m_names[i], this.m_values[i]); } } IEnumerator IEnumerable.GetEnumerator() { - var instance = this as IEnumerable>; + var instance = this as IEnumerable>; return instance.GetEnumerator(); } - public void CopyTo(KeyValuePair[] payloadEntries, int count) + public void CopyTo(KeyValuePair[] payloadEntries, int count) { throw new System.NotSupportedException(); } @@ -123,12 +124,12 @@ public bool Remove(string key) throw new System.NotSupportedException(); } - public bool Remove(KeyValuePair entry) + public bool Remove(KeyValuePair entry) { throw new System.NotSupportedException(); } - public bool TryGetValue(string key, out object value) + public bool TryGetValue(string key, [MaybeNullWhen(false)] out object? value) { if (key == null) throw new System.ArgumentNullException(nameof(key)); @@ -150,7 +151,7 @@ public bool TryGetValue(string key, out object value) #region private private List m_names; - private List m_values; + private List m_values; #endregion } } diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs index 2d71550803cd..37763140159a 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; @@ -92,7 +93,7 @@ public Guid RelatedId /// Allow options (keywords, level) to be set for the write associated with this start /// These will also be used for the stop event. /// The data to include in the event. - public EventSourceActivity Start(string eventName, EventSourceOptions options, T data) + public EventSourceActivity Start(string? eventName, EventSourceOptions options, T data) { return this.Start(eventName, ref options, ref data); } @@ -100,7 +101,7 @@ public EventSourceActivity Start(string eventName, EventSourceOptions options /// Shortcut version see Start(string eventName, EventSourceOptions options, T data) Options is empty (no keywords /// and level==Info) Data payload is empty. /// - public EventSourceActivity Start(string eventName) + public EventSourceActivity Start(string? eventName) { var options = new EventSourceOptions(); var data = new EmptyStruct(); @@ -109,7 +110,7 @@ public EventSourceActivity Start(string eventName) /// /// Shortcut version see Start(string eventName, EventSourceOptions options, T data). Data payload is empty. /// - public EventSourceActivity Start(string eventName, EventSourceOptions options) + public EventSourceActivity Start(string? eventName, EventSourceOptions options) { var data = new EmptyStruct(); return this.Start(eventName, ref options, ref data); @@ -118,7 +119,7 @@ public EventSourceActivity Start(string eventName, EventSourceOptions options) /// Shortcut version see Start(string eventName, EventSourceOptions options, T data) Options is empty (no keywords /// and level==Info) /// - public EventSourceActivity Start(string eventName, T data) + public EventSourceActivity Start(string? eventName, T data) { var options = new EventSourceOptions(); return this.Start(eventName, ref options, ref data); @@ -141,7 +142,7 @@ public void Stop(T data) /// This can be useful to indicate unusual ways of stopping (but it is still STRONGLY recommended that /// you start with the same prefix used for the start event and you end with the 'Stop' suffix. /// - public void Stop(string eventName) + public void Stop(string? eventName) { var data = new EmptyStruct(); this.Stop(eventName, ref data); @@ -151,7 +152,7 @@ public void Stop(string eventName) /// This can be useful to indicate unusual ways of stopping (but it is still STRONGLY recommended that /// you start with the same prefix used for the start event and you end with the 'Stop' suffix. /// - public void Stop(string eventName, T data) + public void Stop(string? eventName, T data) { this.Stop(eventName, ref data); } @@ -168,7 +169,7 @@ public void Stop(string eventName, T data) /// The options to use for the event. /// /// The data to include in the event. - public void Write(string eventName, EventSourceOptions options, T data) + public void Write(string? eventName, EventSourceOptions options, T data) { this.Write(this.eventSource, eventName, ref options, ref data); } @@ -181,7 +182,7 @@ public void Write(string eventName, EventSourceOptions options, T data) /// data's type. /// /// The data to include in the event. - public void Write(string eventName, T data) + public void Write(string? eventName, T data) { var options = new EventSourceOptions(); this.Write(this.eventSource, eventName, ref options, ref data); @@ -196,7 +197,7 @@ public void Write(string eventName, T data) /// /// The options to use for the event. /// - public void Write(string eventName, EventSourceOptions options) + public void Write(string? eventName, EventSourceOptions options) { var data = new EmptyStruct(); this.Write(this.eventSource, eventName, ref options, ref data); @@ -208,7 +209,7 @@ public void Write(string eventName, EventSourceOptions options) /// /// The name to use for the event. Must not be null. /// - public void Write(string eventName) + public void Write(string? eventName) { var options = new EventSourceOptions(); var data = new EmptyStruct(); @@ -217,7 +218,7 @@ public void Write(string eventName) /// /// Writes an event to a arbitrary eventSource stamped with the activity ID of this activity. /// - public void Write(EventSource source, string eventName, EventSourceOptions options, T data) + public void Write(EventSource source, string? eventName, EventSourceOptions options, T data) { this.Write(source, eventName, ref options, ref data); } @@ -236,7 +237,7 @@ public void Dispose() } #region private - private EventSourceActivity Start(string eventName, ref EventSourceOptions options, ref T data) + private EventSourceActivity Start(string? eventName, ref EventSourceOptions options, ref T data) { if (this.state != State.Started) throw new InvalidOperationException(); @@ -265,7 +266,7 @@ private EventSourceActivity Start(string eventName, ref EventSourceOptions op return newActivity; } - private void Write(EventSource eventSource, string eventName, ref EventSourceOptions options, ref T data) + private void Write(EventSource eventSource, string? eventName, ref EventSourceOptions options, ref T data) { if (this.state != State.Started) throw new InvalidOperationException(); // Write after stop. @@ -275,7 +276,7 @@ private void Write(EventSource eventSource, string eventName, ref EventSource eventSource.Write(eventName, ref options, ref this.activityId, ref s_empty, ref data); } - private void Stop(string eventName, ref T data) + private void Stop(string? eventName, ref T data) { if (this.state != State.Started) throw new InvalidOperationException(); @@ -284,6 +285,8 @@ private void Stop(string eventName, ref T data) if (!StartEventWasFired) return; + Debug.Assert(this.eventName != null); + this.state = State.Stopped; if (eventName == null) { @@ -312,7 +315,7 @@ private enum State internal Guid activityId; // internal Guid relatedActivityId; private State state; - private string eventName; + private string? eventName; internal static Guid s_empty; #endregion diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs index f153734752d8..2c50266134cb 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.Resources; using Encoding = System.Text.Encoding; @@ -29,7 +30,7 @@ internal class FieldMetadata /// private readonly int nameSize; private readonly EventFieldTags tags; - private readonly byte[] custom; + private readonly byte[]? custom; /// /// ETW supports fixed sized arrays. If inType has the InTypeFixedCountFlag then this is the @@ -57,7 +58,6 @@ public FieldMetadata( 0, null) { - return; } /// @@ -86,7 +86,7 @@ public FieldMetadata( string name, TraceLoggingDataType type, EventFieldTags tags, - byte[] custom) + byte[]? custom) : this( name, type, @@ -104,7 +104,7 @@ private FieldMetadata( EventFieldTags tags, byte countFlags, ushort fixedCount = 0, - byte[] custom = null) + byte[]? custom = null) { if (name == null) { @@ -172,7 +172,7 @@ public void IncrementStructFieldCount() /// for a 'two pass' approach where you figure out how big to make the array, and then you /// fill it in. /// - public void Encode(ref int pos, byte[] metadata) + public void Encode(ref int pos, byte[]? metadata) { // Write out the null terminated UTF8 encoded name if (metadata != null) @@ -220,7 +220,8 @@ public void Encode(ref int pos, byte[] metadata) { if (metadata != null) { - Buffer.BlockCopy(this.custom, 0, metadata, pos, this.fixedCount); + Debug.Assert(custom != null); + Buffer.BlockCopy(custom, 0, metadata, pos, this.fixedCount); } pos += this.fixedCount; } diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/InvokeTypeInfo.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/InvokeTypeInfo.cs index 23339f1c56c4..34ca1447c386 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/InvokeTypeInfo.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/InvokeTypeInfo.cs @@ -18,14 +18,14 @@ namespace System.Diagnostics.Tracing /// internal sealed class InvokeTypeInfo : TraceLoggingTypeInfo { - internal readonly PropertyAnalysis[] properties; + internal readonly PropertyAnalysis[]? properties; public InvokeTypeInfo( Type type, TypeAnalysis typeAnalysis) : base( type, - typeAnalysis.name, + typeAnalysis.name!, typeAnalysis.level, typeAnalysis.opcode, typeAnalysis.keywords, @@ -37,7 +37,7 @@ public InvokeTypeInfo( public override void WriteMetadata( TraceLoggingMetadataCollector collector, - string name, + string? name, EventFieldFormat format) { var groupCollector = collector.AddGroup(name); @@ -72,12 +72,12 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu } } - public override object GetData(object value) + public override object? GetData(object? value) { if (this.properties != null) { var membersNames = new List(); - var memebersValues = new List(); + var memebersValues = new List(); for (int i = 0; i < this.properties.Length; i++) { var propertyValue = properties[i].propertyInfo.GetValue(value); diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/NameInfo.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/NameInfo.cs index a7daf5e757a2..e1b0cf776e2e 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/NameInfo.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/NameInfo.cs @@ -87,7 +87,7 @@ public IntPtr GetOrCreateEventHandle(EventProvider provider, TraceLoggingEventHa { if ((eventHandle = eventHandleTable[descriptor.EventId]) == IntPtr.Zero) { - byte[] metadataBlob = EventPipeMetadataGenerator.Instance.GenerateEventMetadata( + byte[]? metadataBlob = EventPipeMetadataGenerator.Instance.GenerateEventMetadata( descriptor.EventId, name, (EventKeywords)descriptor.Keywords, diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/PropertyAnalysis.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/PropertyAnalysis.cs index 1f07539b5232..aa79453177ce 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/PropertyAnalysis.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/PropertyAnalysis.cs @@ -21,13 +21,13 @@ internal sealed class PropertyAnalysis internal readonly PropertyInfo propertyInfo; internal readonly Func getter; internal readonly TraceLoggingTypeInfo typeInfo; - internal readonly EventFieldAttribute fieldAttribute; + internal readonly EventFieldAttribute? fieldAttribute; public PropertyAnalysis( string name, PropertyInfo propertyInfo, TraceLoggingTypeInfo typeInfo, - EventFieldAttribute fieldAttribute) + EventFieldAttribute? fieldAttribute) { this.name = name; this.propertyInfo = propertyInfo; diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs index 0f87ea58db39..3d0afdd77433 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs @@ -80,11 +80,11 @@ public struct Scalar } // Anything not covered by the Scalar union gets stored in this reference. - readonly object _reference; + readonly object? _reference; readonly Scalar _scalar; readonly int _scalarLength; - private PropertyValue(object value) + private PropertyValue(object? value) { _reference = value; _scalar = default; @@ -118,33 +118,32 @@ private PropertyValue(DateTimeOffset value) : this(new Scalar() { AsDateTimeOffs private PropertyValue(TimeSpan value) : this(new Scalar() { AsTimeSpan = value }, sizeof(TimeSpan)) { } private PropertyValue(decimal value) : this(new Scalar() { AsDecimal = value }, sizeof(decimal)) { } - public static Func GetFactory(Type type) + public static Func GetFactory(Type type) { - if (type == typeof(bool)) return value => new PropertyValue((bool)value); - if (type == typeof(byte)) return value => new PropertyValue((byte)value); - if (type == typeof(sbyte)) return value => new PropertyValue((sbyte)value); - if (type == typeof(char)) return value => new PropertyValue((char)value); - if (type == typeof(short)) return value => new PropertyValue((short)value); - if (type == typeof(ushort)) return value => new PropertyValue((ushort)value); - if (type == typeof(int)) return value => new PropertyValue((int)value); - if (type == typeof(uint)) return value => new PropertyValue((uint)value); - if (type == typeof(long)) return value => new PropertyValue((long)value); - if (type == typeof(ulong)) return value => new PropertyValue((ulong)value); - if (type == typeof(IntPtr)) return value => new PropertyValue((IntPtr)value); - if (type == typeof(UIntPtr)) return value => new PropertyValue((UIntPtr)value); - if (type == typeof(float)) return value => new PropertyValue((float)value); - if (type == typeof(double)) return value => new PropertyValue((double)value); - if (type == typeof(Guid)) return value => new PropertyValue((Guid)value); - if (type == typeof(DateTime)) return value => new PropertyValue((DateTime)value); - if (type == typeof(DateTimeOffset)) return value => new PropertyValue((DateTimeOffset)value); - if (type == typeof(TimeSpan)) return value => new PropertyValue((TimeSpan)value); - if (type == typeof(decimal)) return value => new PropertyValue((decimal)value); + if (type == typeof(bool)) return value => new PropertyValue((bool)value!); + if (type == typeof(byte)) return value => new PropertyValue((byte)value!); + if (type == typeof(sbyte)) return value => new PropertyValue((sbyte)value!); + if (type == typeof(char)) return value => new PropertyValue((char)value!); + if (type == typeof(short)) return value => new PropertyValue((short)value!); + if (type == typeof(ushort)) return value => new PropertyValue((ushort)value!); + if (type == typeof(int)) return value => new PropertyValue((int)value!); + if (type == typeof(uint)) return value => new PropertyValue((uint)value!); + if (type == typeof(long)) return value => new PropertyValue((long)value!); + if (type == typeof(ulong)) return value => new PropertyValue((ulong)value!); + if (type == typeof(IntPtr)) return value => new PropertyValue((IntPtr)value!); + if (type == typeof(UIntPtr)) return value => new PropertyValue((UIntPtr)value!); + if (type == typeof(float)) return value => new PropertyValue((float)value!); + if (type == typeof(double)) return value => new PropertyValue((double)value!); + if (type == typeof(Guid)) return value => new PropertyValue((Guid)value!); + if (type == typeof(DateTime)) return value => new PropertyValue((DateTime)value!); + if (type == typeof(DateTimeOffset)) return value => new PropertyValue((DateTimeOffset)value!); + if (type == typeof(TimeSpan)) return value => new PropertyValue((TimeSpan)value!); + if (type == typeof(decimal)) return value => new PropertyValue((decimal)value!); return value => new PropertyValue(value); } - - public object ReferenceValue + public object? ReferenceValue { get { @@ -176,7 +175,7 @@ public int ScalarLength /// public static Func GetPropertyGetter(PropertyInfo property) { - if (property.DeclaringType.GetTypeInfo().IsValueType) + if (property.DeclaringType!.GetTypeInfo().IsValueType) return GetBoxedValueTypePropertyGetter(property); else return GetReferenceTypePropertyGetter(property); @@ -209,7 +208,7 @@ private static Func GetBoxedValueTypePropertyGette /// private static Func GetReferenceTypePropertyGetter(PropertyInfo property) { - var helper = (TypeHelper)Activator.CreateInstance(typeof(ReferenceTypeHelper<>).MakeGenericType(property.DeclaringType)); + var helper = (TypeHelper)Activator.CreateInstance(typeof(ReferenceTypeHelper<>).MakeGenericType(property.DeclaringType!))!; return helper.GetPropertyGetter(property); } @@ -224,7 +223,7 @@ abstract class TypeHelper protected Delegate GetGetMethod(PropertyInfo property, Type propertyType) { - return property.GetMethod.CreateDelegate(typeof(Func<,>).MakeGenericType(property.DeclaringType, propertyType)); + return property.GetMethod!.CreateDelegate(typeof(Func<,>).MakeGenericType(property.DeclaringType!, propertyType)); } } @@ -233,7 +232,7 @@ protected Delegate GetGetMethod(PropertyInfo property, Type propertyType) #else private #endif - sealed class ReferenceTypeHelper : TypeHelper where TContainer : class + sealed class ReferenceTypeHelper : TypeHelper where TContainer : class? { public override Func GetPropertyGetter(PropertyInfo property) { @@ -241,33 +240,33 @@ public override Func GetPropertyGetter(PropertyInf if (!Statics.IsValueType(type)) { - var getter = (Func)GetGetMethod(property, type); - return container => new PropertyValue(getter((TContainer)container.ReferenceValue)); + var getter = (Func)GetGetMethod(property, type); + return container => new PropertyValue(getter((TContainer)container.ReferenceValue!)); } else { if (type.GetTypeInfo().IsEnum) type = Enum.GetUnderlyingType(type); - if (type == typeof(bool)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(byte)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(sbyte)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(char)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(short)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(ushort)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(int)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(uint)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(long)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(ulong)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(IntPtr)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(UIntPtr)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(float)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(double)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Guid)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(DateTime)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(DateTimeOffset)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(TimeSpan)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(decimal)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(bool)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(byte)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(sbyte)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(char)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(short)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(ushort)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(int)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(uint)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(long)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(ulong)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(IntPtr)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(UIntPtr)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(float)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(double)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(Guid)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(DateTime)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(DateTimeOffset)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(TimeSpan)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } + if (type == typeof(decimal)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } return container => new PropertyValue(property.GetValue(container.ReferenceValue)); } diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/SimpleEventTypes.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/SimpleEventTypes.cs index cdced968f057..74cde08e307f 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/SimpleEventTypes.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/SimpleEventTypes.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using Interlocked = System.Threading.Interlocked; #if ES_BUILD_STANDALONE @@ -21,7 +22,7 @@ namespace System.Diagnostics.Tracing /// internal static class SimpleEventTypes { - private static TraceLoggingEventTypes instance; + private static TraceLoggingEventTypes? instance; public static TraceLoggingEventTypes Instance { @@ -33,6 +34,7 @@ private static TraceLoggingEventTypes InitInstance() var info = TraceLoggingTypeInfo.GetInstance(typeof(T), null); var newInstance = new TraceLoggingEventTypes(info.Name, info.Tags, new TraceLoggingTypeInfo[] { info }); Interlocked.CompareExchange(ref instance, newInstance, null); + Debug.Assert(instance != null); return instance; } } diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs index dc714d860ec8..b957de00eebb 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs @@ -28,7 +28,7 @@ public NullTypeInfo() : base(typeof(EmptyStruct)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, - string name, + string? name, EventFieldFormat format) { collector.AddGroup(name); @@ -39,7 +39,7 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu return; } - public override object GetData(object value) + public override object? GetData(object? value) { return null; } @@ -63,9 +63,9 @@ private ScalarTypeInfo( this.nativeFormat = nativeFormat; } - public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) + public override void WriteMetadata(TraceLoggingMetadataCollector collector, string? name, EventFieldFormat format) { - collector.AddScalar(name, formatFunc(format, nativeFormat)); + collector.AddScalar(name!, formatFunc(format, nativeFormat)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) @@ -112,9 +112,9 @@ private ScalarArrayTypeInfo( this.elementSize = elementSize; } - public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) + public override void WriteMetadata(TraceLoggingMetadataCollector collector, string? name, EventFieldFormat format) { - collector.AddArray(name, formatFunc(format, nativeFormat)); + collector.AddArray(name!, formatFunc(format, nativeFormat)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) @@ -148,20 +148,20 @@ public StringTypeInfo() : base(typeof(string)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, - string name, + string? name, EventFieldFormat format) { - collector.AddNullTerminatedString(name, Statics.MakeDataType(TraceLoggingDataType.Utf16String, format)); + collector.AddNullTerminatedString(name!, Statics.MakeDataType(TraceLoggingDataType.Utf16String, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { - collector.AddNullTerminatedString((string)value.ReferenceValue); + collector.AddNullTerminatedString((string?)value.ReferenceValue); } - public override object GetData(object value) + public override object GetData(object? value) { - if(value == null) + if (value == null) { return ""; } @@ -179,10 +179,10 @@ public DateTimeTypeInfo() : base(typeof(DateTime)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, - string name, + string? name, EventFieldFormat format) { - collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.FileTime, format)); + collector.AddScalar(name!, Statics.MakeDataType(TraceLoggingDataType.FileTime, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) @@ -205,7 +205,7 @@ internal sealed class DateTimeOffsetTypeInfo : TraceLoggingTypeInfo { public DateTimeOffsetTypeInfo() : base(typeof(DateTimeOffset)) { } - public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) + public override void WriteMetadata(TraceLoggingMetadataCollector collector, string? name, EventFieldFormat format) { var group = collector.AddGroup(name); group.AddScalar("Ticks", Statics.MakeDataType(TraceLoggingDataType.FileTime, format)); @@ -230,10 +230,10 @@ public TimeSpanTypeInfo() : base(typeof(TimeSpan)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, - string name, + string? name, EventFieldFormat format) { - collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Int64, format)); + collector.AddScalar(name!, Statics.MakeDataType(TraceLoggingDataType.Int64, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) @@ -251,10 +251,10 @@ public DecimalTypeInfo() : base(typeof(decimal)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, - string name, + string? name, EventFieldFormat format) { - collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Double, format)); + collector.AddScalar(name!, Statics.MakeDataType(TraceLoggingDataType.Double, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) @@ -277,12 +277,12 @@ public NullableTypeInfo(Type type, List recursionCheck) var typeArgs = type.GenericTypeArguments; Debug.Assert(typeArgs.Length == 1); this.valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck); - this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value")); + this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value")!); } public override void WriteMetadata( TraceLoggingMetadataCollector collector, - string name, + string? name, EventFieldFormat format) { var group = collector.AddGroup(name); diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/Statics.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/Statics.cs index 0c21672131c1..0affe93dea7b 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/Statics.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/Statics.cs @@ -10,6 +10,7 @@ using Encoding = System.Text.Encoding; using Microsoft.Reflection; +using System.Diagnostics.CodeAnalysis; #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; @@ -112,7 +113,7 @@ public static byte[] MetadataForString( /// This is useful for a two pass approach where you figure out how big to /// make the array, and then you fill it in. /// - public static void EncodeTags(int tags, ref int pos, byte[] metadata) + public static void EncodeTags(int tags, ref int pos, byte[]? metadata) { // We transmit the low 28 bits of tags, high bits first, 7 bits at a time. var tagsLeft = tags & 0xfffffff; @@ -172,7 +173,7 @@ public static int Combine( } } - public static void CheckName(string name) + public static void CheckName(string? name) { if (name != null && 0 <= name.IndexOf('\0')) { @@ -363,7 +364,7 @@ All TraceLogging use of reflection APIs should go through wrappers here. kinds of reflection operations are being done. */ - public static object CreateInstance(Type type, params object[] parameters) + public static object? CreateInstance(Type type, params object?[]? parameters) { return Activator.CreateInstance(type, parameters); } @@ -386,15 +387,15 @@ public static IEnumerable GetProperties(Type type) return result; } - public static MethodInfo GetGetMethod(PropertyInfo propInfo) + public static MethodInfo? GetGetMethod(PropertyInfo propInfo) { - MethodInfo result = propInfo.GetGetMethod(); + MethodInfo? result = propInfo.GetGetMethod(); return result; } - public static MethodInfo GetDeclaredStaticMethod(Type declaringType, string name) + public static MethodInfo? GetDeclaredStaticMethod(Type declaringType, string name) { - MethodInfo result; + MethodInfo? result; #if (ES_BUILD_PCL || ES_BUILD_PN) result = declaringType.GetTypeInfo().GetDeclaredMethod(name); #else @@ -421,10 +422,10 @@ public static bool HasCustomAttribute( return result; } - public static AttributeType GetCustomAttribute(PropertyInfo propInfo) + public static AttributeType? GetCustomAttribute(PropertyInfo propInfo) where AttributeType : Attribute { - AttributeType result = null; + AttributeType? result = null; #if (ES_BUILD_PCL || ES_BUILD_PN) foreach (var attrib in propInfo.GetCustomAttributes(false)) { @@ -441,10 +442,10 @@ public static AttributeType GetCustomAttribute(PropertyInfo propI return result; } - public static AttributeType GetCustomAttribute(Type type) + public static AttributeType? GetCustomAttribute(Type type) where AttributeType : Attribute { - AttributeType result = null; + AttributeType? result = null; #if (ES_BUILD_PCL || ES_BUILD_PN) foreach (var attrib in type.GetTypeInfo().GetCustomAttributes(false)) { @@ -466,9 +467,9 @@ public static Type[] GetGenericArguments(Type type) return type.GetGenericArguments(); } - public static Type FindEnumerableElementType(Type type) + public static Type? FindEnumerableElementType(Type type) { - Type elementType = null; + Type? elementType = null; if (IsGenericMatch(type, typeof(IEnumerable<>))) { @@ -505,9 +506,9 @@ public static Type FindEnumerableElementType(Type type) return elementType; } - public static bool IsGenericMatch(Type type, object openType) + public static bool IsGenericMatch(Type type, object? openType) { - return type.IsGenericType() && type.GetGenericTypeDefinition() == (Type)openType; + return type.IsGenericType() && type.GetGenericTypeDefinition() == (Type?)openType; } public static Delegate CreateDelegate(Type delegateType, MethodInfo methodInfo) @@ -547,7 +548,7 @@ public static TraceLoggingTypeInfo CreateDefaultTypeInfo( } else if (dataType.IsArray) { - var elementType = dataType.GetElementType(); + Type elementType = dataType.GetElementType()!; if (elementType == typeof(bool)) { result = ScalarArrayTypeInfo.Boolean(); diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataCollector.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataCollector.cs index c6f89c8784e6..419f0f264787 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataCollector.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataCollector.cs @@ -99,7 +99,7 @@ public void AddScalar(bool value) /// /// Value to be added. A null value is treated as a zero-length string. /// - public void AddNullTerminatedString(string value) + public void AddNullTerminatedString(string? value) { DataCollector.ThreadInstance.AddNullTerminatedString(value); } @@ -110,14 +110,14 @@ public void AddNullTerminatedString(string value) /// /// Value to be added. A null value is treated as a zero-length string. /// - public void AddBinary(string value) + public void AddBinary(string? value) { DataCollector.ThreadInstance.AddBinary(value, value == null ? 0 : value.Length * 2); } public void AddArray(PropertyValue value, int elementSize) { - Array array = (Array)value.ReferenceValue; + Array? array = (Array?)value.ReferenceValue; DataCollector.ThreadInstance.AddArray(array, array == null ? 0 : array.Length, elementSize); } } diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs index 0553f9899936..b737da4c1145 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs @@ -20,6 +20,7 @@ #endif using System; +using System.Diagnostics; using System.Resources; using System.Runtime.InteropServices; using System.Security; @@ -44,7 +45,7 @@ namespace System.Diagnostics.Tracing public partial class EventSource { #if FEATURE_MANAGED_ETW - private byte[] providerMetadata; + private byte[] providerMetadata = null!; #endif #if FEATURE_PERFTRACING @@ -93,10 +94,10 @@ public EventSource( public EventSource( string eventSourceName, EventSourceSettings config, - params string[] traits) + params string[]? traits) : this( eventSourceName == null ? new Guid() : GenerateGuidFromName(eventSourceName.ToUpperInvariant()), - eventSourceName, + eventSourceName!, config, traits) { if (eventSourceName == null) @@ -170,7 +171,7 @@ public unsafe void Write(string eventName, EventSourceOptions options) /// create the fields of the event. /// public unsafe void Write( - string eventName, + string? eventName, T data) { if (!this.IsEnabled()) @@ -206,7 +207,7 @@ public unsafe void Write( /// create the fields of the event. /// public unsafe void Write( - string eventName, + string? eventName, EventSourceOptions options, T data) { @@ -244,7 +245,7 @@ public unsafe void Write( /// create the fields of the event. /// public unsafe void Write( - string eventName, + string? eventName, ref EventSourceOptions options, ref T data) { @@ -289,7 +290,7 @@ public unsafe void Write( /// create the fields of the event. /// public unsafe void Write( - string eventName, + string? eventName, ref EventSourceOptions options, ref Guid activityId, ref Guid relatedActivityId, @@ -345,7 +346,7 @@ public unsafe void Write( /// eventTypes parameter. /// private unsafe void WriteMultiMerge( - string eventName, + string? eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, @@ -405,7 +406,7 @@ private unsafe void WriteMultiMerge( /// eventTypes parameter. /// private unsafe void WriteMultiMergeInner( - string eventName, + string? eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, @@ -528,7 +529,7 @@ private unsafe void WriteMultiMergeInner( /// fields described by the eventTypes parameter. /// internal unsafe void WriteMultiMerge( - string eventName, + string? eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, @@ -600,9 +601,9 @@ internal unsafe void WriteMultiMerge( } private unsafe void WriteImpl( - string eventName, + string? eventName, ref EventSourceOptions options, - object data, + object? data, Guid* pActivityId, Guid* pRelatedActivityId, TraceLoggingEventTypes eventTypes) @@ -630,7 +631,7 @@ private unsafe void WriteImpl( var pinCount = eventTypes.pinCount; var scratch = stackalloc byte[eventTypes.scratchSize]; var descriptors = stackalloc EventData[eventTypes.dataCount + 3]; - for(int i=0; i((IList)payload.Values); + eventCallbackArgs.Payload = new ReadOnlyCollection((IList)payload.Values); eventCallbackArgs.PayloadNames = new ReadOnlyCollection((IList)payload.Keys); } @@ -875,13 +878,13 @@ private static int HexDigit(char c) throw new ArgumentException(SR.Format(SR.EventSource_BadHexDigit, c), "traits"); } - private NameInfo UpdateDescriptor( - string name, + private NameInfo? UpdateDescriptor( + string? name, TraceLoggingEventTypes eventInfo, ref EventSourceOptions options, out EventDescriptor descriptor) { - NameInfo nameInfo = null; + NameInfo? nameInfo = null; int identity = 0; byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs index 8887714fdb1a..9ff1ccaf53e9 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs @@ -26,7 +26,7 @@ public class TraceLoggingEventTypes { internal readonly TraceLoggingTypeInfo[] typeInfos; #if FEATURE_PERFTRACING - internal readonly string[] paramNames; + internal readonly string[]? paramNames; #endif internal readonly string name; internal readonly EventTags tags; @@ -60,7 +60,6 @@ internal TraceLoggingEventTypes( params Type[] types) : this(tags, name, MakeArray(types)) { - return; } /// @@ -87,7 +86,6 @@ internal TraceLoggingEventTypes( params TraceLoggingTypeInfo[] typeInfos) : this(tags, name, MakeArray(typeInfos)) { - return; } internal TraceLoggingEventTypes( @@ -116,7 +114,7 @@ internal TraceLoggingEventTypes( this.opcode = Statics.Combine((int)typeInfo.Opcode, this.opcode); this.keywords |= typeInfo.Keywords; var paramName = paramInfos[i].Name; - if (Statics.ShouldOverrideFieldName(paramName)) + if (Statics.ShouldOverrideFieldName(paramName!)) { paramName = typeInfo.Name; } @@ -262,7 +260,7 @@ private static string[] MakeParamNameArray( string[] paramNames = new string[paramInfos.Length]; for (int i = 0; i < paramNames.Length; i++) { - paramNames[i] = paramInfos[i].Name; + paramNames[i] = paramInfos[i].Name!; } return paramNames; diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingMetadataCollector.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingMetadataCollector.cs index b5b199dbca7d..8b522e85697b 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingMetadataCollector.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingMetadataCollector.cs @@ -19,7 +19,7 @@ namespace System.Diagnostics.Tracing internal class TraceLoggingMetadataCollector { private readonly Impl impl; - private readonly FieldMetadata currentGroup; + private readonly FieldMetadata? currentGroup; private int bufferedArrayFieldCount = int.MinValue; /// @@ -93,7 +93,7 @@ private bool BeginningBufferedArray /// /// A new metadata collector that can be used to add fields to the group. /// - public TraceLoggingMetadataCollector AddGroup(string name) + public TraceLoggingMetadataCollector AddGroup(string? name) { TraceLoggingMetadataCollector result = this; @@ -101,7 +101,7 @@ public TraceLoggingMetadataCollector AddGroup(string name) this.BeginningBufferedArray) // Error, FieldMetadata's constructor will throw the appropriate exception. { var newGroup = new FieldMetadata( - name, + name!, TraceLoggingDataType.Struct, this.Tags, this.BeginningBufferedArray); @@ -375,7 +375,7 @@ public void EndBuffered() this.bufferNesting--; } - public int Encode(byte[] metadata) + public int Encode(byte[]? metadata) { int size = 0; diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs index 511a4fe480c8..f31765c2f3aa 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs @@ -30,7 +30,7 @@ internal abstract class TraceLoggingTypeInfo private readonly EventOpcode opcode = (EventOpcode)(-1); private readonly EventTags tags; private readonly Type dataType; - private readonly Func propertyValueFactory; + private readonly Func propertyValueFactory; internal TraceLoggingTypeInfo(Type dataType) { @@ -124,7 +124,7 @@ internal Type DataType get { return this.dataType; } } - internal Func PropertyValueFactory + internal Func PropertyValueFactory { get { return this.propertyValueFactory; } } @@ -153,7 +153,7 @@ internal Func PropertyValueFactory /// public abstract void WriteMetadata( TraceLoggingMetadataCollector collector, - string name, + string? name, EventFieldFormat format); /// @@ -177,15 +177,15 @@ public abstract void WriteData( /// /// /// - public virtual object GetData(object value) + public virtual object? GetData(object? value) { return value; } [ThreadStatic] // per-thread cache to avoid synchronization - private static Dictionary threadCache; + private static Dictionary? threadCache; - public static TraceLoggingTypeInfo GetInstance(Type type, List recursionCheck) + public static TraceLoggingTypeInfo GetInstance(Type type, List? recursionCheck) { var cache = threadCache ?? (threadCache = new Dictionary()); diff --git a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TypeAnalysis.cs b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TypeAnalysis.cs index 42cdde5f6ad8..ff99f5ea5802 100644 --- a/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TypeAnalysis.cs +++ b/src/Common/src/CoreLib/System/Diagnostics/Tracing/TraceLogging/TypeAnalysis.cs @@ -19,7 +19,7 @@ namespace System.Diagnostics.Tracing internal sealed class TypeAnalysis { internal readonly PropertyAnalysis[] properties; - internal readonly string name; + internal readonly string? name; internal readonly EventKeywords keywords; internal readonly EventLevel level = (EventLevel)(-1); internal readonly EventOpcode opcode = (EventOpcode)(-1); @@ -27,7 +27,7 @@ internal sealed class TypeAnalysis public TypeAnalysis( Type dataType, - EventDataAttribute eventAttrib, + EventDataAttribute? eventAttrib, List recursionCheck) { var propertyInfos = Statics.GetProperties(dataType); @@ -46,7 +46,7 @@ public TypeAnalysis( continue; } - MethodInfo getterInfo = Statics.GetGetMethod(propertyInfo); + MethodInfo? getterInfo = Statics.GetGetMethod(propertyInfo); if (getterInfo == null) { continue; diff --git a/src/Common/src/CoreLib/System/DivideByZeroException.cs b/src/Common/src/CoreLib/System/DivideByZeroException.cs index 8b04145eb330..8c079fb60463 100644 --- a/src/Common/src/CoreLib/System/DivideByZeroException.cs +++ b/src/Common/src/CoreLib/System/DivideByZeroException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/DllNotFoundException.cs b/src/Common/src/CoreLib/System/DllNotFoundException.cs index 0165d1aa7c61..b9c3e05afaa8 100644 --- a/src/Common/src/CoreLib/System/DllNotFoundException.cs +++ b/src/Common/src/CoreLib/System/DllNotFoundException.cs @@ -12,7 +12,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/Double.cs b/src/Common/src/CoreLib/System/Double.cs index 85b797ae8c4a..806add021ae5 100644 --- a/src/Common/src/CoreLib/System/Double.cs +++ b/src/Common/src/CoreLib/System/Double.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ -#nullable enable using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/DuplicateWaitObjectException.cs b/src/Common/src/CoreLib/System/DuplicateWaitObjectException.cs index 2fbe337f560f..0aef5d6bd7e9 100644 --- a/src/Common/src/CoreLib/System/DuplicateWaitObjectException.cs +++ b/src/Common/src/CoreLib/System/DuplicateWaitObjectException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/Empty.cs b/src/Common/src/CoreLib/System/Empty.cs index 64c54dca029e..186b92078e87 100644 --- a/src/Common/src/CoreLib/System/Empty.cs +++ b/src/Common/src/CoreLib/System/Empty.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { #if CORERT diff --git a/src/Common/src/CoreLib/System/EntryPointNotFoundException.cs b/src/Common/src/CoreLib/System/EntryPointNotFoundException.cs index f88e07b93fc8..e8b735c44b53 100644 --- a/src/Common/src/CoreLib/System/EntryPointNotFoundException.cs +++ b/src/Common/src/CoreLib/System/EntryPointNotFoundException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System; using System.Runtime.Serialization; diff --git a/src/Common/src/CoreLib/System/Enum.cs b/src/Common/src/CoreLib/System/Enum.cs index 2f6ea1e79731..df7c1eeadd8d 100644 --- a/src/Common/src/CoreLib/System/Enum.cs +++ b/src/Common/src/CoreLib/System/Enum.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; @@ -494,7 +494,7 @@ private static bool TryParse(string? value, bool ignoreCase, bool throwOn default: parsed = TryParseRareEnum(rt, value, valueSpan, ignoreCase, throwOnFailure, out object? objectResult); - result = parsed ? (TEnum)objectResult : default; + result = parsed ? (TEnum)objectResult! : default; return parsed; } } @@ -646,7 +646,7 @@ private static bool TryParseUInt64Enum(RuntimeType enumType, string? originalVal } /// Tries to parse the value of an enum with an underlying type that can't be expressed in C# (e.g. char, bool, double, etc.) - private static bool TryParseRareEnum(RuntimeType enumType, string? originalValueString, ReadOnlySpan value, bool ignoreCase, bool throwOnFailure, out object? result) + private static bool TryParseRareEnum(RuntimeType enumType, string? originalValueString, ReadOnlySpan value, bool ignoreCase, bool throwOnFailure, [NotNullWhen(true)] out object? result) { Debug.Assert( enumType.GetEnumUnderlyingType() != typeof(sbyte) && diff --git a/src/Common/src/CoreLib/System/Environment.NoRegistry.cs b/src/Common/src/CoreLib/System/Environment.NoRegistry.cs index 4ba66bdb03e4..6e699b1f3861 100644 --- a/src/Common/src/CoreLib/System/Environment.NoRegistry.cs +++ b/src/Common/src/CoreLib/System/Environment.NoRegistry.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Collections; using Microsoft.Win32; diff --git a/src/Common/src/CoreLib/System/Environment.SpecialFolder.cs b/src/Common/src/CoreLib/System/Environment.SpecialFolder.cs index 5e7d0549e49d..ae2add730d2b 100644 --- a/src/Common/src/CoreLib/System/Environment.SpecialFolder.cs +++ b/src/Common/src/CoreLib/System/Environment.SpecialFolder.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { public static partial class Environment diff --git a/src/Common/src/CoreLib/System/Environment.SpecialFolderOption.cs b/src/Common/src/CoreLib/System/Environment.SpecialFolderOption.cs index 05972a701bf7..929e3d9036a1 100644 --- a/src/Common/src/CoreLib/System/Environment.SpecialFolderOption.cs +++ b/src/Common/src/CoreLib/System/Environment.SpecialFolderOption.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { public static partial class Environment diff --git a/src/Common/src/CoreLib/System/Environment.Unix.cs b/src/Common/src/CoreLib/System/Environment.Unix.cs index d74086b0fc4c..0d802dcec909 100644 --- a/src/Common/src/CoreLib/System/Environment.Unix.cs +++ b/src/Common/src/CoreLib/System/Environment.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; @@ -76,14 +75,16 @@ private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOptio { Debug.Assert(option == SpecialFolderOption.Create); +#pragma warning disable CS8634 // TODO-NULLABLE: Remove warning disable when nullable attributes are respected // TODO #11151: Replace with Directory.CreateDirectory once we have access to System.IO.FileSystem here. Func createDirectory = LazyInitializer.EnsureInitialized(ref s_directoryCreateDirectory, () => { - Type dirType = Type.GetType("System.IO.Directory, System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: true); - MethodInfo mi = dirType.GetTypeInfo().GetDeclaredMethod("CreateDirectory"); + Type dirType = Type.GetType("System.IO.Directory, System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: true)!; + MethodInfo mi = dirType.GetTypeInfo().GetDeclaredMethod("CreateDirectory")!; return (Func)mi.CreateDelegate(typeof(Func)); - })!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + })!; // TODO-NULLABLE: Remove ! when nullable attributes are respected createDirectory(path); +#pragma warning restore CS8634 return path; } diff --git a/src/Common/src/CoreLib/System/Environment.Variables.Windows.cs b/src/Common/src/CoreLib/System/Environment.Variables.Windows.cs index c13410207f49..80c88d76701c 100644 --- a/src/Common/src/CoreLib/System/Environment.Variables.Windows.cs +++ b/src/Common/src/CoreLib/System/Environment.Variables.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers; using System.Collections; using System.Diagnostics; diff --git a/src/Common/src/CoreLib/System/Environment.Win32.cs b/src/Common/src/CoreLib/System/Environment.Win32.cs index f58cdcf5bc1a..d536f5ccb44f 100644 --- a/src/Common/src/CoreLib/System/Environment.Win32.cs +++ b/src/Common/src/CoreLib/System/Environment.Win32.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections; using System.Diagnostics; using System.IO; @@ -15,6 +14,8 @@ namespace System { public static partial class Environment { + internal static bool IsWindows8OrAbove => WindowsVersion.IsWindows8OrAbove; + private static string? GetEnvironmentVariableFromRegistry(string variable, bool fromMachine) { Debug.Assert(variable != null); @@ -79,7 +80,7 @@ private static IDictionary GetEnvironmentVariablesFromRegistry(bool fromMachine) { foreach (string name in environmentKey.GetValueNames()) { - string? value = environmentKey.GetValue(name, "")!.ToString(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + string? value = environmentKey.GetValue(name, "")!.ToString(); // TODO-NULLABLE: Remove ! when nullable attributes are respected try { results.Add(name, value); @@ -409,7 +410,7 @@ public static string GetFolderPath(SpecialFolder folder, SpecialFolderOption opt { if (s_winRTFolderPathsGetFolderPath == null) { - Type winRtFolderPathsType = Type.GetType("System.WinRTFolderPaths, System.Runtime.WindowsRuntime, Version=4.0.14.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", throwOnError: false); + Type? winRtFolderPathsType = Type.GetType("System.WinRTFolderPaths, System.Runtime.WindowsRuntime, Version=4.0.14.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", throwOnError: false); MethodInfo? getFolderPathsMethod = winRtFolderPathsType?.GetMethod("GetFolderPath", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(SpecialFolder), typeof(SpecialFolderOption) }, null); var d = (Func?)getFolderPathsMethod?.CreateDelegate(typeof(Func)); s_winRTFolderPathsGetFolderPath = d ?? delegate { return string.Empty; }; @@ -419,5 +420,35 @@ public static string GetFolderPath(SpecialFolder folder, SpecialFolderOption opt } } #endif + + // Seperate type so a .cctor is not created for Enviroment which then would be triggered during startup + private static class WindowsVersion + { + // Cache the value in readonly static that can be optimized out by the JIT + internal readonly static bool IsWindows8OrAbove = GetIsWindows8OrAbove(); + + private static bool GetIsWindows8OrAbove() + { + ulong conditionMask = Interop.Kernel32.VerSetConditionMask(0, Interop.Kernel32.VER_MAJORVERSION, Interop.Kernel32.VER_GREATER_EQUAL); + conditionMask = Interop.Kernel32.VerSetConditionMask(conditionMask, Interop.Kernel32.VER_MINORVERSION, Interop.Kernel32.VER_GREATER_EQUAL); + conditionMask = Interop.Kernel32.VerSetConditionMask(conditionMask, Interop.Kernel32.VER_SERVICEPACKMAJOR, Interop.Kernel32.VER_GREATER_EQUAL); + conditionMask = Interop.Kernel32.VerSetConditionMask(conditionMask, Interop.Kernel32.VER_SERVICEPACKMINOR, Interop.Kernel32.VER_GREATER_EQUAL); + + // Windows 8 version is 6.2 + Interop.Kernel32.OSVERSIONINFOEX version = default; + unsafe + { + version.dwOSVersionInfoSize = sizeof(Interop.Kernel32.OSVERSIONINFOEX); + } + version.dwMajorVersion = 6; + version.dwMinorVersion = 2; + version.wServicePackMajor = 0; + version.wServicePackMinor = 0; + + return Interop.Kernel32.VerifyVersionInfoW(ref version, + Interop.Kernel32.VER_MAJORVERSION | Interop.Kernel32.VER_MINORVERSION | Interop.Kernel32.VER_SERVICEPACKMAJOR | Interop.Kernel32.VER_SERVICEPACKMINOR, + conditionMask); + } + } } } diff --git a/src/Common/src/CoreLib/System/Environment.WinRT.cs b/src/Common/src/CoreLib/System/Environment.WinRT.cs index 814b7c430122..9a4bb8608a13 100644 --- a/src/Common/src/CoreLib/System/Environment.WinRT.cs +++ b/src/Common/src/CoreLib/System/Environment.WinRT.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.IO; using Internal.Runtime.Augments; @@ -14,6 +13,8 @@ public static partial class Environment public static string UserDomainName => "Windows Domain"; + internal static readonly bool IsWindows8OrAbove = true; + private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option) { WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; diff --git a/src/Common/src/CoreLib/System/Environment.Windows.cs b/src/Common/src/CoreLib/System/Environment.Windows.cs index f60323b27d23..957d1894a2a8 100644 --- a/src/Common/src/CoreLib/System/Environment.Windows.cs +++ b/src/Common/src/CoreLib/System/Environment.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.IO; using System.Runtime.InteropServices; using System.Text; diff --git a/src/Common/src/CoreLib/System/Environment.cs b/src/Common/src/CoreLib/System/Environment.cs index 3691c0de2b7e..319ae9b1c61c 100644 --- a/src/Common/src/CoreLib/System/Environment.cs +++ b/src/Common/src/CoreLib/System/Environment.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections; using System.Diagnostics; using System.Reflection; @@ -123,7 +122,7 @@ public static OperatingSystem OSVersion { Interlocked.CompareExchange(ref s_osVersion, GetOSVersion(), null); } - return s_osVersion!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + return s_osVersion!; // TODO-NULLABLE: Remove ! when compiler specially-recognizes CompareExchange for nullability } } @@ -150,7 +149,7 @@ public static Version Version versionSpan = versionSpan.Slice(0, separatorIndex); // Return zeros rather then failing if the version string fails to parse - return Version.TryParse(versionSpan, out Version? version) ? version! : new Version(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + return Version.TryParse(versionSpan, out Version? version) ? version! : new Version(); // TODO-NULLABLE: Remove ! when nullable attributes are respected } } @@ -162,13 +161,13 @@ public static long WorkingSet // we do this to avoid duplicating the Windows, Linux, macOS, and potentially other platform-specific implementations // present in Process. If it proves important, we could look at separating that functionality out of Process into // Common files which could also be included here. - Type processType = Type.GetType("System.Diagnostics.Process, System.Diagnostics.Process, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false); + Type? processType = Type.GetType("System.Diagnostics.Process, System.Diagnostics.Process, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false); IDisposable? currentProcess = processType?.GetMethod("GetCurrentProcess")?.Invoke(null, BindingFlags.DoNotWrapExceptions, null, null, null) as IDisposable; if (currentProcess != null) { using (currentProcess) { - object? result = processType!.GetMethod("get_WorkingSet64")?.Invoke(currentProcess, BindingFlags.DoNotWrapExceptions, null, null, null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/2388 + object? result = processType!.GetMethod("get_WorkingSet64")?.Invoke(currentProcess, BindingFlags.DoNotWrapExceptions, null, null, null); if (result is long) return (long)result; } } diff --git a/src/Common/src/CoreLib/System/EnvironmentVariableTarget.cs b/src/Common/src/CoreLib/System/EnvironmentVariableTarget.cs index 1f8213cb5645..a592832ce59c 100644 --- a/src/Common/src/CoreLib/System/EnvironmentVariableTarget.cs +++ b/src/Common/src/CoreLib/System/EnvironmentVariableTarget.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { #if PROJECTN diff --git a/src/Common/src/CoreLib/System/EventArgs.cs b/src/Common/src/CoreLib/System/EventArgs.cs index 0d806c6312ac..f3561a8d0b14 100644 --- a/src/Common/src/CoreLib/System/EventArgs.cs +++ b/src/Common/src/CoreLib/System/EventArgs.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; namespace System diff --git a/src/Common/src/CoreLib/System/EventHandler.cs b/src/Common/src/CoreLib/System/EventHandler.cs index 7e0f183438f9..89c5de022bad 100644 --- a/src/Common/src/CoreLib/System/EventHandler.cs +++ b/src/Common/src/CoreLib/System/EventHandler.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; namespace System diff --git a/src/Common/src/CoreLib/System/Exception.cs b/src/Common/src/CoreLib/System/Exception.cs index 0fc37ee78bed..521ade0e194a 100644 --- a/src/Common/src/CoreLib/System/Exception.cs +++ b/src/Common/src/CoreLib/System/Exception.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections; using System.Runtime.Serialization; @@ -141,15 +140,10 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte } public override string ToString() - { - return ToString(true, true); - } - - private string ToString(bool needFileLineInfo, bool needMessage) { string s = GetClassName(); - string? message = (needMessage ? Message : null); + string? message = Message; if (!string.IsNullOrEmpty(message)) { s += ": " + message; @@ -157,11 +151,11 @@ private string ToString(bool needFileLineInfo, bool needMessage) if (_innerException != null) { - s = s + " ---> " + _innerException.ToString(needFileLineInfo, needMessage) + Environment.NewLine + + s = s + " ---> " + _innerException.ToString() + Environment.NewLine + " " + SR.Exception_EndOfInnerExceptionStack; } - string? stackTrace = GetStackTrace(needFileLineInfo); + string? stackTrace = GetStackTrace(needFileInfo: true); if (stackTrace != null) { s += Environment.NewLine + stackTrace; diff --git a/src/Common/src/CoreLib/System/ExecutionEngineException.cs b/src/Common/src/CoreLib/System/ExecutionEngineException.cs index 30979888909a..2d6da9ca2f97 100644 --- a/src/Common/src/CoreLib/System/ExecutionEngineException.cs +++ b/src/Common/src/CoreLib/System/ExecutionEngineException.cs @@ -15,7 +15,6 @@ ** =============================================================================*/ -#nullable enable using System; using System.Runtime.Serialization; diff --git a/src/Common/src/CoreLib/System/FieldAccessException.cs b/src/Common/src/CoreLib/System/FieldAccessException.cs index c0b2bd663089..20b4bd95164f 100644 --- a/src/Common/src/CoreLib/System/FieldAccessException.cs +++ b/src/Common/src/CoreLib/System/FieldAccessException.cs @@ -9,7 +9,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/FlagsAttribute.cs b/src/Common/src/CoreLib/System/FlagsAttribute.cs index 751f944f838d..4f3ab36bfd5a 100644 --- a/src/Common/src/CoreLib/System/FlagsAttribute.cs +++ b/src/Common/src/CoreLib/System/FlagsAttribute.cs @@ -5,7 +5,6 @@ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -#nullable enable namespace System { // Custom attribute to indicate that the enum diff --git a/src/Common/src/CoreLib/System/FormatException.cs b/src/Common/src/CoreLib/System/FormatException.cs index 9fefdca15ef3..f5639f2fc98f 100644 --- a/src/Common/src/CoreLib/System/FormatException.cs +++ b/src/Common/src/CoreLib/System/FormatException.cs @@ -11,7 +11,6 @@ ** ===========================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/FormattableString.cs b/src/Common/src/CoreLib/System/FormattableString.cs index 965a916bc3ec..73b1981cd718 100644 --- a/src/Common/src/CoreLib/System/FormattableString.cs +++ b/src/Common/src/CoreLib/System/FormattableString.cs @@ -11,7 +11,6 @@ ** ===========================================================*/ -#nullable enable namespace System { /// diff --git a/src/Common/src/CoreLib/System/Gen2GcCallback.cs b/src/Common/src/CoreLib/System/Gen2GcCallback.cs index 72d11a90db65..063c6ce0a0e6 100644 --- a/src/Common/src/CoreLib/System/Gen2GcCallback.cs +++ b/src/Common/src/CoreLib/System/Gen2GcCallback.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable +using System.Diagnostics; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; @@ -14,15 +14,31 @@ namespace System /// internal sealed class Gen2GcCallback : CriticalFinalizerObject { - private readonly Func _callback; + private readonly Func? _callback0; + private readonly Func? _callback1; private readonly GCHandle _weakTargetObj; + private Gen2GcCallback(Func callback) + { + _callback0 = callback; + } + private Gen2GcCallback(Func callback, object targetObj) { - _callback = callback; + _callback1 = callback; _weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak); } + /// + /// Schedule 'callback' to be called in the next GC. If the callback returns true it is + /// rescheduled for the next Gen 2 GC. Otherwise the callbacks stop. + /// + public static void Register(Func callback) + { + // Create a unreachable object that remembers the callback function and target object. + new Gen2GcCallback(callback); + } + /// /// Schedule 'callback' to be called in the next GC. If the callback returns true it is /// rescheduled for the next Gen 2 GC. Otherwise the callbacks stop. @@ -38,38 +54,60 @@ public static void Register(Func callback, object targetObj) ~Gen2GcCallback() { - // Check to see if the target object is still alive. - object? targetObj = _weakTargetObj.Target; - if (targetObj == null) - { - // The target object is dead, so this callback object is no longer needed. - _weakTargetObj.Free(); - return; - } - - // Execute the callback method. - try + if (_weakTargetObj.IsAllocated) { - if (!_callback(targetObj)) + // Check to see if the target object is still alive. + object? targetObj = _weakTargetObj.Target; + if (targetObj == null) { - // If the callback returns false, this callback object is no longer needed. + // The target object is dead, so this callback object is no longer needed. + _weakTargetObj.Free(); return; } + + // Execute the callback method. + try + { + Debug.Assert(_callback1 != null); + if (!_callback1(targetObj)) + { + // If the callback returns false, this callback object is no longer needed. + return; + } + } + catch + { + // Ensure that we still get a chance to resurrect this object, even if the callback throws an exception. +#if DEBUG + // Except in DEBUG, as we really shouldn't be hitting any exceptions here. + throw; +#endif + } } - catch + else { - // Ensure that we still get a chance to resurrect this object, even if the callback throws an exception. + // Execute the callback method. + try + { + Debug.Assert(_callback0 != null); + if (!_callback0()) + { + // If the callback returns false, this callback object is no longer needed. + return; + } + } + catch + { + // Ensure that we still get a chance to resurrect this object, even if the callback throws an exception. #if DEBUG - // Except in DEBUG, as we really shouldn't be hitting any exceptions here. - throw; + // Except in DEBUG, as we really shouldn't be hitting any exceptions here. + throw; #endif + } } // Resurrect ourselves by re-registering for finalization. - if (!Environment.HasShutdownStarted) - { - GC.ReRegisterForFinalize(this); - } + GC.ReRegisterForFinalize(this); } } } diff --git a/src/Common/src/CoreLib/System/Globalization/Calendar.cs b/src/Common/src/CoreLib/System/Globalization/Calendar.cs index aa9a07111dc9..4460d3d06a22 100644 --- a/src/Common/src/CoreLib/System/Globalization/Calendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/Calendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.Serialization; diff --git a/src/Common/src/CoreLib/System/Globalization/CalendarData.Unix.cs b/src/Common/src/CoreLib/System/Globalization/CalendarData.Unix.cs index 80e385376d05..c1495706caef 100644 --- a/src/Common/src/CoreLib/System/Globalization/CalendarData.Unix.cs +++ b/src/Common/src/CoreLib/System/Globalization/CalendarData.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Security; @@ -36,10 +35,15 @@ internal partial class CalendarData private bool LoadCalendarDataFromSystem(string localeName, CalendarId calendarId) { bool result = true; - // TODO-NULLABLE: these can return null but are later replaced with String.Empty or other non-nullable value + + // these can return null but are later replaced with String.Empty or other non-nullable value result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out this.sNativeName!); result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.MonthDay, out this.sMonthDay!); - this.sMonthDay = NormalizeDatePattern(this.sMonthDay); + + if (this.sMonthDay != null) + { + this.sMonthDay = NormalizeDatePattern(this.sMonthDay); + } result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.ShortDates, out this.saShortDates!); result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.LongDates, out this.saLongDates!); diff --git a/src/Common/src/CoreLib/System/Globalization/CalendarData.Windows.cs b/src/Common/src/CoreLib/System/Globalization/CalendarData.Windows.cs index 84e4ddf5f2df..bee8ab8ce30a 100644 --- a/src/Common/src/CoreLib/System/Globalization/CalendarData.Windows.cs +++ b/src/Common/src/CoreLib/System/Globalization/CalendarData.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Diagnostics; using System.Runtime.InteropServices; @@ -101,10 +100,10 @@ private bool LoadCalendarDataFromSystem(string localeName, CalendarId calendarId // // Clean up the escaping of the formats - this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 - this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 - this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 - this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates)!; + this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates)!; + this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths)!; + this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay)!; return ret; } diff --git a/src/Common/src/CoreLib/System/Globalization/CalendarData.cs b/src/Common/src/CoreLib/System/Globalization/CalendarData.cs index 131dd6b31550..aae2c00ffa91 100644 --- a/src/Common/src/CoreLib/System/Globalization/CalendarData.cs +++ b/src/Common/src/CoreLib/System/Globalization/CalendarData.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Globalization @@ -14,10 +13,6 @@ namespace System.Globalization // NOTE: Calendars depend on the locale name that creates it. Only a few // properties are available without locales using CalendarData.GetCalendar(CalendarData) // - // TODO-NULLABLE: this class requires refactoring for proper annotations - // currently from user of this class all fields are non-nullable. - // To avoid potential breaking changes lots of workaround have - // been used to suppress errors internal partial class CalendarData { // Max calendars @@ -112,7 +107,8 @@ internal CalendarData(string localeName, CalendarId calendarId, bool bUseUserOve if (!LoadCalendarDataFromSystem(localeName, calendarId)) { - Debug.Fail("[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName); + // LoadCalendarDataFromSystem sometimes can fail on Linux if the installed ICU package is missing some resources. + // The ICU package can miss some resources in some cases like if someone compile and build the ICU package manually or ICU has a regression. // Something failed, try invariant for missing parts // This is really not good, but we don't want the callers to crash. diff --git a/src/Common/src/CoreLib/System/Globalization/CalendricalCalculationsHelper.cs b/src/Common/src/CoreLib/System/Globalization/CalendricalCalculationsHelper.cs index a0fb75978a4f..241019a0bc31 100644 --- a/src/Common/src/CoreLib/System/Globalization/CalendricalCalculationsHelper.cs +++ b/src/Common/src/CoreLib/System/Globalization/CalendricalCalculationsHelper.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Globalization/CharUnicodeInfo.cs b/src/Common/src/CoreLib/System/Globalization/CharUnicodeInfo.cs index a78965b3e23b..e627cc7483fd 100644 --- a/src/Common/src/CoreLib/System/Globalization/CharUnicodeInfo.cs +++ b/src/Common/src/CoreLib/System/Globalization/CharUnicodeInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers.Binary; using System.Diagnostics; using System.Text; diff --git a/src/Common/src/CoreLib/System/Globalization/CharUnicodeInfoData.cs b/src/Common/src/CoreLib/System/Globalization/CharUnicodeInfoData.cs index 1af4cfeb56cd..95aac2f35576 100644 --- a/src/Common/src/CoreLib/System/Globalization/CharUnicodeInfoData.cs +++ b/src/Common/src/CoreLib/System/Globalization/CharUnicodeInfoData.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { public static partial class CharUnicodeInfo diff --git a/src/Common/src/CoreLib/System/Globalization/ChineseLunisolarCalendar.cs b/src/Common/src/CoreLib/System/Globalization/ChineseLunisolarCalendar.cs index c7c129f338fc..b35508c5d039 100644 --- a/src/Common/src/CoreLib/System/Globalization/ChineseLunisolarCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/ChineseLunisolarCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { /// diff --git a/src/Common/src/CoreLib/System/Globalization/CompareInfo.Invariant.cs b/src/Common/src/CoreLib/System/Globalization/CompareInfo.Invariant.cs index d579dbefcbb8..16201b8d1faa 100644 --- a/src/Common/src/CoreLib/System/Globalization/CompareInfo.Invariant.cs +++ b/src/Common/src/CoreLib/System/Globalization/CompareInfo.Invariant.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/Globalization/CompareInfo.Unix.cs b/src/Common/src/CoreLib/System/Globalization/CompareInfo.Unix.cs index bbb07a753552..c915c9d2275d 100644 --- a/src/Common/src/CoreLib/System/Globalization/CompareInfo.Unix.cs +++ b/src/Common/src/CoreLib/System/Globalization/CompareInfo.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/Globalization/CompareInfo.Windows.cs b/src/Common/src/CoreLib/System/Globalization/CompareInfo.Windows.cs index b706ad50e1de..7f1ba8ca917f 100644 --- a/src/Common/src/CoreLib/System/Globalization/CompareInfo.Windows.cs +++ b/src/Common/src/CoreLib/System/Globalization/CompareInfo.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/Globalization/CompareInfo.cs b/src/Common/src/CoreLib/System/Globalization/CompareInfo.cs index ef2eb4945afc..dd4da0de0676 100644 --- a/src/Common/src/CoreLib/System/Globalization/CompareInfo.cs +++ b/src/Common/src/CoreLib/System/Globalization/CompareInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; @@ -171,8 +170,8 @@ public static unsafe bool IsSortable(string text) [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { - // TODO-NULLABLE: this becomes null for a brief moment before deserialization - // after serialization is finished it is never null + // this becomes null for a brief moment before deserialization + // after serialization is finished it is never null. m_name = null!; } diff --git a/src/Common/src/CoreLib/System/Globalization/CultureData.Unix.cs b/src/Common/src/CoreLib/System/Globalization/CultureData.Unix.cs index f1a2669b9797..56f24820517e 100644 --- a/src/Common/src/CoreLib/System/Globalization/CultureData.Unix.cs +++ b/src/Common/src/CoreLib/System/Globalization/CultureData.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; @@ -265,6 +264,19 @@ private static string ConvertIcuTimeFormatString(ReadOnlySpan icuFormatStr { switch (icuFormatString[i]) { + case '\'': + result[resultPos++] = icuFormatString[i++]; + while (i < icuFormatString.Length) + { + char current = icuFormatString[i++]; + result[resultPos++] = current; + if (current == '\'') + { + break; + } + } + break; + case ':': case '.': case 'H': diff --git a/src/Common/src/CoreLib/System/Globalization/CultureData.Windows.cs b/src/Common/src/CoreLib/System/Globalization/CultureData.Windows.cs index f92f119b4b3c..28315b91dbde 100644 --- a/src/Common/src/CoreLib/System/Globalization/CultureData.Windows.cs +++ b/src/Common/src/CoreLib/System/Globalization/CultureData.Windows.cs @@ -2,10 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Text; using Internal.Runtime.CompilerServices; @@ -357,6 +356,7 @@ private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bo /// /// We don't build the stringbuilder unless we find something to change /// + [return: NotNullIfNotNull("str")] internal static string? ReescapeWin32String(string? str) { // If we don't have data, then don't try anything @@ -425,13 +425,14 @@ private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bo return result.ToString(); } + [return: NotNullIfNotNull("array")] internal static string[]? ReescapeWin32Strings(string[]? array) { if (array != null) { for (int i = 0; i < array.Length; i++) { - array[i] = ReescapeWin32String(array[i])!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + array[i] = ReescapeWin32String(array[i])!; // TODO-NULLABLE: Remove ! when nullable attributes are respected } } diff --git a/src/Common/src/CoreLib/System/Globalization/CultureData.cs b/src/Common/src/CoreLib/System/Globalization/CultureData.cs index c86bab5afacb..d29668e17384 100644 --- a/src/Common/src/CoreLib/System/Globalization/CultureData.cs +++ b/src/Common/src/CoreLib/System/Globalization/CultureData.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Text; @@ -797,9 +796,9 @@ internal string CultureName { case "zh-CHS": case "zh-CHT": - return _sName!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34273 + return _sName; } - return _sRealName!; + return _sRealName; } } diff --git a/src/Common/src/CoreLib/System/Globalization/CultureInfo.Unix.cs b/src/Common/src/CoreLib/System/Globalization/CultureInfo.Unix.cs index 0973ee0876d9..2a16ab6111f0 100644 --- a/src/Common/src/CoreLib/System/Globalization/CultureInfo.Unix.cs +++ b/src/Common/src/CoreLib/System/Globalization/CultureInfo.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Globalization/CultureInfo.Windows.cs b/src/Common/src/CoreLib/System/Globalization/CultureInfo.Windows.cs index 8d312dfc5c49..d746659fd2c0 100644 --- a/src/Common/src/CoreLib/System/Globalization/CultureInfo.Windows.cs +++ b/src/Common/src/CoreLib/System/Globalization/CultureInfo.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable #if FEATURE_APPX using System.Resources; using Internal.Resources; @@ -40,7 +39,7 @@ internal static CultureInfo GetUserDefaultCulture() return GetCultureByName(strDefault); } - private static CultureInfo GetUserDefaultUICulture() + private unsafe static CultureInfo GetUserDefaultUICulture() { #if !ENABLE_WINRT if (GlobalizationMode.Invariant) @@ -50,18 +49,21 @@ private static CultureInfo GetUserDefaultUICulture() uint langCount = 0; uint bufLen = 0; - if (Interop.Kernel32.GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, out langCount, null, ref bufLen)) + if (Interop.Kernel32.GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &langCount, null, &bufLen) != Interop.BOOL.FALSE) { char[] languages = new char[bufLen]; - if (Interop.Kernel32.GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, out langCount, languages, ref bufLen)) + fixed (char* pLanguages = languages) { - int index = 0; - while (languages[index] != (char)0 && index < languages.Length) + if (Interop.Kernel32.GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &langCount, pLanguages, &bufLen) != Interop.BOOL.FALSE) { - index++; - } + int index = 0; + while (languages[index] != (char)0 && index < languages.Length) + { + index++; + } - return GetCultureByName(new string(languages, 0, index)); + return GetCultureByName(new string(languages, 0, index)); + } } } #endif diff --git a/src/Common/src/CoreLib/System/Globalization/CultureInfo.cs b/src/Common/src/CoreLib/System/Globalization/CultureInfo.cs index 643327ce12e7..76c966646e24 100644 --- a/src/Common/src/CoreLib/System/Globalization/CultureInfo.cs +++ b/src/Common/src/CoreLib/System/Globalization/CultureInfo.cs @@ -26,7 +26,6 @@ // //////////////////////////////////////////////////////////////////////////// -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Threading; diff --git a/src/Common/src/CoreLib/System/Globalization/CultureNotFoundException.cs b/src/Common/src/CoreLib/System/Globalization/CultureNotFoundException.cs index 87d26f8a6735..e17385564b5c 100644 --- a/src/Common/src/CoreLib/System/Globalization/CultureNotFoundException.cs +++ b/src/Common/src/CoreLib/System/Globalization/CultureNotFoundException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Globalization/DateTimeFormat.cs b/src/Common/src/CoreLib/System/Globalization/DateTimeFormat.cs index c2b20c46bfc9..6f6d10ab94a7 100644 --- a/src/Common/src/CoreLib/System/Globalization/DateTimeFormat.cs +++ b/src/Common/src/CoreLib/System/Globalization/DateTimeFormat.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Globalization; diff --git a/src/Common/src/CoreLib/System/Globalization/DateTimeFormatInfo.cs b/src/Common/src/CoreLib/System/Globalization/DateTimeFormatInfo.cs index 78c97903ceda..b091f7a60364 100644 --- a/src/Common/src/CoreLib/System/Globalization/DateTimeFormatInfo.cs +++ b/src/Common/src/CoreLib/System/Globalization/DateTimeFormatInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/Globalization/DateTimeFormatInfoScanner.cs b/src/Common/src/CoreLib/System/Globalization/DateTimeFormatInfoScanner.cs index a43bfe777bd9..2005cf3b7341 100644 --- a/src/Common/src/CoreLib/System/Globalization/DateTimeFormatInfoScanner.cs +++ b/src/Common/src/CoreLib/System/Globalization/DateTimeFormatInfoScanner.cs @@ -19,7 +19,6 @@ // //////////////////////////////////////////////////////////////////////////// -#nullable enable using System.Collections.Generic; using System.Text; diff --git a/src/Common/src/CoreLib/System/Globalization/DateTimeParse.cs b/src/Common/src/CoreLib/System/Globalization/DateTimeParse.cs index 107fac5e6cd8..511a440588c0 100644 --- a/src/Common/src/CoreLib/System/Globalization/DateTimeParse.cs +++ b/src/Common/src/CoreLib/System/Globalization/DateTimeParse.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; @@ -192,7 +191,7 @@ internal static bool TryParseExactMultiple(ReadOnlySpan s, string?[]? form // for (int i = 0; i < formats.Length; i++) { - if (formats[i] == null || formats[i]!.Length == 0) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 + if (formats[i] == null || formats[i]!.Length == 0) // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) { result.SetBadFormatSpecifierFailure(); return false; diff --git a/src/Common/src/CoreLib/System/Globalization/DaylightTime.cs b/src/Common/src/CoreLib/System/Globalization/DaylightTime.cs index 0569b390c792..72a572c97de5 100644 --- a/src/Common/src/CoreLib/System/Globalization/DaylightTime.cs +++ b/src/Common/src/CoreLib/System/Globalization/DaylightTime.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { // This class represents a starting/ending time for a period of daylight saving time. diff --git a/src/Common/src/CoreLib/System/Globalization/EastAsianLunisolarCalendar.cs b/src/Common/src/CoreLib/System/Globalization/EastAsianLunisolarCalendar.cs index aa7d1fb0a35b..621524aaa819 100644 --- a/src/Common/src/CoreLib/System/Globalization/EastAsianLunisolarCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/EastAsianLunisolarCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { public abstract class EastAsianLunisolarCalendar : Calendar diff --git a/src/Common/src/CoreLib/System/Globalization/GlobalizationExtensions.cs b/src/Common/src/CoreLib/System/Globalization/GlobalizationExtensions.cs index ed00cc58f6b9..007283aa6b10 100644 --- a/src/Common/src/CoreLib/System/Globalization/GlobalizationExtensions.cs +++ b/src/Common/src/CoreLib/System/Globalization/GlobalizationExtensions.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Diagnostics; diff --git a/src/Common/src/CoreLib/System/Globalization/GregorianCalendar.cs b/src/Common/src/CoreLib/System/Globalization/GregorianCalendar.cs index 68aba7e0352f..ebc5a54f4025 100644 --- a/src/Common/src/CoreLib/System/Globalization/GregorianCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/GregorianCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { /// diff --git a/src/Common/src/CoreLib/System/Globalization/GregorianCalendarHelper.cs b/src/Common/src/CoreLib/System/Globalization/GregorianCalendarHelper.cs index 5889dcb2759a..efa47fe273b3 100644 --- a/src/Common/src/CoreLib/System/Globalization/GregorianCalendarHelper.cs +++ b/src/Common/src/CoreLib/System/Globalization/GregorianCalendarHelper.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Threading; diff --git a/src/Common/src/CoreLib/System/Globalization/HebrewCalendar.cs b/src/Common/src/CoreLib/System/Globalization/HebrewCalendar.cs index 314c99816dd0..d72e3817b19f 100644 --- a/src/Common/src/CoreLib/System/Globalization/HebrewCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/HebrewCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Globalization/HebrewNumber.cs b/src/Common/src/CoreLib/System/Globalization/HebrewNumber.cs index 1919e826773e..a2054377d5dd 100644 --- a/src/Common/src/CoreLib/System/Globalization/HebrewNumber.cs +++ b/src/Common/src/CoreLib/System/Globalization/HebrewNumber.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Text; using System.Diagnostics; diff --git a/src/Common/src/CoreLib/System/Globalization/HijriCalendar.Unix.cs b/src/Common/src/CoreLib/System/Globalization/HijriCalendar.Unix.cs index 2b7b35f2ea79..a6e8f73d3e44 100644 --- a/src/Common/src/CoreLib/System/Globalization/HijriCalendar.Unix.cs +++ b/src/Common/src/CoreLib/System/Globalization/HijriCalendar.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { public partial class HijriCalendar : Calendar diff --git a/src/Common/src/CoreLib/System/Globalization/HijriCalendar.Win32.cs b/src/Common/src/CoreLib/System/Globalization/HijriCalendar.Win32.cs index 1e8f7474d170..75988535e395 100644 --- a/src/Common/src/CoreLib/System/Globalization/HijriCalendar.Win32.cs +++ b/src/Common/src/CoreLib/System/Globalization/HijriCalendar.Win32.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Internal.Win32; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Globalization/HijriCalendar.WinRT.cs b/src/Common/src/CoreLib/System/Globalization/HijriCalendar.WinRT.cs index 85b9afef3051..fb91c27ef62a 100644 --- a/src/Common/src/CoreLib/System/Globalization/HijriCalendar.WinRT.cs +++ b/src/Common/src/CoreLib/System/Globalization/HijriCalendar.WinRT.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Internal.Runtime.Augments; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Globalization/HijriCalendar.cs b/src/Common/src/CoreLib/System/Globalization/HijriCalendar.cs index 41458c5a1251..910294eda277 100644 --- a/src/Common/src/CoreLib/System/Globalization/HijriCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/HijriCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { /// diff --git a/src/Common/src/CoreLib/System/Globalization/ISOWeek.cs b/src/Common/src/CoreLib/System/Globalization/ISOWeek.cs index 89f5ca4a26cb..60715713b195 100644 --- a/src/Common/src/CoreLib/System/Globalization/ISOWeek.cs +++ b/src/Common/src/CoreLib/System/Globalization/ISOWeek.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using static System.Globalization.GregorianCalendar; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Globalization/IdnMapping.Unix.cs b/src/Common/src/CoreLib/System/Globalization/IdnMapping.Unix.cs index 4c8dcb871991..ad15040cfc75 100644 --- a/src/Common/src/CoreLib/System/Globalization/IdnMapping.Unix.cs +++ b/src/Common/src/CoreLib/System/Globalization/IdnMapping.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Globalization/IdnMapping.Windows.cs b/src/Common/src/CoreLib/System/Globalization/IdnMapping.Windows.cs index 696abbcde1f5..6a97c04ebf66 100644 --- a/src/Common/src/CoreLib/System/Globalization/IdnMapping.Windows.cs +++ b/src/Common/src/CoreLib/System/Globalization/IdnMapping.Windows.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace System.Globalization @@ -115,6 +115,7 @@ private uint Flags } } + [DoesNotReturn] private static void ThrowForZeroLength(bool unicode) { int lastError = Marshal.GetLastWin32Error(); diff --git a/src/Common/src/CoreLib/System/Globalization/IdnMapping.cs b/src/Common/src/CoreLib/System/Globalization/IdnMapping.cs index 9da4411f10e2..63aa4e1097f1 100644 --- a/src/Common/src/CoreLib/System/Globalization/IdnMapping.cs +++ b/src/Common/src/CoreLib/System/Globalization/IdnMapping.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable // This file contains the IDN functions and implementation. // // This allows encoding of non-ASCII domain names in a "punycode" form, diff --git a/src/Common/src/CoreLib/System/Globalization/InternalGlobalizationHelper.cs b/src/Common/src/CoreLib/System/Globalization/InternalGlobalizationHelper.cs index 59fcd0f3c759..6dc2b1951561 100644 --- a/src/Common/src/CoreLib/System/Globalization/InternalGlobalizationHelper.cs +++ b/src/Common/src/CoreLib/System/Globalization/InternalGlobalizationHelper.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { internal class InternalGlobalizationHelper diff --git a/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.Unix.cs b/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.Unix.cs index 364eeef05971..0bbebba77428 100644 --- a/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.Unix.cs +++ b/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections.Generic; using System.Diagnostics; diff --git a/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.Win32.cs b/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.Win32.cs index 780b9533fd69..ffea420e7c1f 100644 --- a/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.Win32.cs +++ b/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.Win32.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using Internal.Win32; @@ -93,10 +92,10 @@ public partial class JapaneseCalendar : Calendar Array.Resize(ref registryEraRanges, iFoundEras); // Sort them - Array.Sort(registryEraRanges!, CompareEraRanges); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + Array.Sort(registryEraRanges!, CompareEraRanges); // TODO-NULLABLE: Remove ! when nullable attributes are respected // Clean up era information - for (int i = 0; i < registryEraRanges!.Length; i++) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + for (int i = 0; i < registryEraRanges!.Length; i++) // TODO-NULLABLE: Remove ! when nullable attributes are respected { // eras count backwards from length to 1 (and are 1 based indexes into string arrays) registryEraRanges[i].era = registryEraRanges.Length - i; diff --git a/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.WinRT.cs b/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.WinRT.cs index ce770695f0be..15fe8984591e 100644 --- a/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.WinRT.cs +++ b/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.WinRT.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using Internal.Runtime.Augments; diff --git a/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.cs b/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.cs index 90f03d561311..b0428db0a538 100644 --- a/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/JapaneseCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { /// diff --git a/src/Common/src/CoreLib/System/Globalization/JapaneseLunisolarCalendar.cs b/src/Common/src/CoreLib/System/Globalization/JapaneseLunisolarCalendar.cs index ce1b941077b8..cdaded6bc3e7 100644 --- a/src/Common/src/CoreLib/System/Globalization/JapaneseLunisolarCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/JapaneseLunisolarCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { /// @@ -202,7 +201,7 @@ private static EraInfo[] TrimEras(EraInfo[] baseEras) // If we didn't copy any then something was wrong, just return base if (newIndex == 0) return baseEras; - Array.Resize(ref newEras!, newIndex); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + Array.Resize(ref newEras!, newIndex); // TODO-NULLABLE: Remove ! when nullable attributes are respected return newEras; } diff --git a/src/Common/src/CoreLib/System/Globalization/JulianCalendar.cs b/src/Common/src/CoreLib/System/Globalization/JulianCalendar.cs index 782e197750c3..bba7f07053a9 100644 --- a/src/Common/src/CoreLib/System/Globalization/JulianCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/JulianCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { /// diff --git a/src/Common/src/CoreLib/System/Globalization/KoreanCalendar.cs b/src/Common/src/CoreLib/System/Globalization/KoreanCalendar.cs index a29f4d25e4c6..699b484b24d3 100644 --- a/src/Common/src/CoreLib/System/Globalization/KoreanCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/KoreanCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { /// diff --git a/src/Common/src/CoreLib/System/Globalization/KoreanLunisolarCalendar.cs b/src/Common/src/CoreLib/System/Globalization/KoreanLunisolarCalendar.cs index 5871436ee0cf..1204d722e2c7 100644 --- a/src/Common/src/CoreLib/System/Globalization/KoreanLunisolarCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/KoreanLunisolarCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { /// diff --git a/src/Common/src/CoreLib/System/Globalization/LocaleData.Unix.cs b/src/Common/src/CoreLib/System/Globalization/LocaleData.Unix.cs index 6b5049c2baf1..aab78082dfa3 100644 --- a/src/Common/src/CoreLib/System/Globalization/LocaleData.Unix.cs +++ b/src/Common/src/CoreLib/System/Globalization/LocaleData.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; // This file contains the handling of Windows OS specific culture features. diff --git a/src/Common/src/CoreLib/System/Globalization/Normalization.Unix.cs b/src/Common/src/CoreLib/System/Globalization/Normalization.Unix.cs index 79a28322bc47..37c9024c33d4 100644 --- a/src/Common/src/CoreLib/System/Globalization/Normalization.Unix.cs +++ b/src/Common/src/CoreLib/System/Globalization/Normalization.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Text; diff --git a/src/Common/src/CoreLib/System/Globalization/Normalization.Windows.cs b/src/Common/src/CoreLib/System/Globalization/Normalization.Windows.cs index 0b3ce0ec86ae..b04a6729f213 100644 --- a/src/Common/src/CoreLib/System/Globalization/Normalization.Windows.cs +++ b/src/Common/src/CoreLib/System/Globalization/Normalization.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; diff --git a/src/Common/src/CoreLib/System/Globalization/NumberFormatInfo.cs b/src/Common/src/CoreLib/System/Globalization/NumberFormatInfo.cs index bd490e42adb9..3078c8e57625 100644 --- a/src/Common/src/CoreLib/System/Globalization/NumberFormatInfo.cs +++ b/src/Common/src/CoreLib/System/Globalization/NumberFormatInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { /// diff --git a/src/Common/src/CoreLib/System/Globalization/PersianCalendar.cs b/src/Common/src/CoreLib/System/Globalization/PersianCalendar.cs index 0e43b15a1288..40f9c9c84616 100644 --- a/src/Common/src/CoreLib/System/Globalization/PersianCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/PersianCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Globalization/RegionInfo.cs b/src/Common/src/CoreLib/System/Globalization/RegionInfo.cs index 30471095f065..ccaa806adb69 100644 --- a/src/Common/src/CoreLib/System/Globalization/RegionInfo.cs +++ b/src/Common/src/CoreLib/System/Globalization/RegionInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Globalization/SortKey.cs b/src/Common/src/CoreLib/System/Globalization/SortKey.cs index f75b4f74ab9d..0b2a8a33ade0 100644 --- a/src/Common/src/CoreLib/System/Globalization/SortKey.cs +++ b/src/Common/src/CoreLib/System/Globalization/SortKey.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Globalization/SortVersion.cs b/src/Common/src/CoreLib/System/Globalization/SortVersion.cs index 23cf8b37d79a..89c3fa29fa09 100644 --- a/src/Common/src/CoreLib/System/Globalization/SortVersion.cs +++ b/src/Common/src/CoreLib/System/Globalization/SortVersion.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; namespace System.Globalization @@ -45,7 +44,9 @@ public override bool Equals(object? obj) return obj is SortVersion otherVersion && Equals(otherVersion); } +#pragma warning disable CS8614 // TODO-NULLABLE: Covariant interface arguments (https://github.com/dotnet/roslyn/issues/35817) public bool Equals(SortVersion? other) +#pragma warning restore CS8614 { if (other == null) { diff --git a/src/Common/src/CoreLib/System/Globalization/StringInfo.cs b/src/Common/src/CoreLib/System/Globalization/StringInfo.cs index fe5db920ef4a..0e6a7cfdcad2 100644 --- a/src/Common/src/CoreLib/System/Globalization/StringInfo.cs +++ b/src/Common/src/CoreLib/System/Globalization/StringInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Globalization/TaiwanCalendar.cs b/src/Common/src/CoreLib/System/Globalization/TaiwanCalendar.cs index de541a30c4aa..e190f663775d 100644 --- a/src/Common/src/CoreLib/System/Globalization/TaiwanCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/TaiwanCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics.CodeAnalysis; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Globalization/TaiwanLunisolarCalendar.cs b/src/Common/src/CoreLib/System/Globalization/TaiwanLunisolarCalendar.cs index 47dbc3b0af23..13a2a635669d 100644 --- a/src/Common/src/CoreLib/System/Globalization/TaiwanLunisolarCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/TaiwanLunisolarCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { /// diff --git a/src/Common/src/CoreLib/System/Globalization/TextElementEnumerator.cs b/src/Common/src/CoreLib/System/Globalization/TextElementEnumerator.cs index 4e34474f36fb..5ff3d84520ad 100644 --- a/src/Common/src/CoreLib/System/Globalization/TextElementEnumerator.cs +++ b/src/Common/src/CoreLib/System/Globalization/TextElementEnumerator.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections; using System.Diagnostics; @@ -51,7 +50,9 @@ public bool MoveNext() return true; } - public object? Current => GetTextElement(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 +#pragma warning disable CS8612 // TODO-NULLABLE: Covariant return types (https://github.com/dotnet/roslyn/issues/23268) + public object Current => GetTextElement(); +#pragma warning restore CS8612 public string GetTextElement() { diff --git a/src/Common/src/CoreLib/System/Globalization/TextInfo.Unix.cs b/src/Common/src/CoreLib/System/Globalization/TextInfo.Unix.cs index 5f75e6c050d6..45cf55c56ebc 100644 --- a/src/Common/src/CoreLib/System/Globalization/TextInfo.Unix.cs +++ b/src/Common/src/CoreLib/System/Globalization/TextInfo.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; diff --git a/src/Common/src/CoreLib/System/Globalization/TextInfo.Windows.cs b/src/Common/src/CoreLib/System/Globalization/TextInfo.Windows.cs index b59648dae586..d0c859400b5d 100644 --- a/src/Common/src/CoreLib/System/Globalization/TextInfo.Windows.cs +++ b/src/Common/src/CoreLib/System/Globalization/TextInfo.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Globalization/TextInfo.cs b/src/Common/src/CoreLib/System/Globalization/TextInfo.cs index 4391dec044fd..38005a0c6bb8 100644 --- a/src/Common/src/CoreLib/System/Globalization/TextInfo.cs +++ b/src/Common/src/CoreLib/System/Globalization/TextInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/Globalization/ThaiBuddhistCalendar.cs b/src/Common/src/CoreLib/System/Globalization/ThaiBuddhistCalendar.cs index 8997f00f265d..8bc48db3f952 100644 --- a/src/Common/src/CoreLib/System/Globalization/ThaiBuddhistCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/ThaiBuddhistCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Globalization { /// diff --git a/src/Common/src/CoreLib/System/Globalization/TimeSpanFormat.cs b/src/Common/src/CoreLib/System/Globalization/TimeSpanFormat.cs index 376827e6fd97..fe565435d85a 100644 --- a/src/Common/src/CoreLib/System/Globalization/TimeSpanFormat.cs +++ b/src/Common/src/CoreLib/System/Globalization/TimeSpanFormat.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers.Text; using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/Globalization/TimeSpanParse.cs b/src/Common/src/CoreLib/System/Globalization/TimeSpanParse.cs index a03a02c1f8b1..6b4ea6a7c936 100644 --- a/src/Common/src/CoreLib/System/Globalization/TimeSpanParse.cs +++ b/src/Common/src/CoreLib/System/Globalization/TimeSpanParse.cs @@ -48,7 +48,6 @@ // //////////////////////////////////////////////////////////////////////////// -#nullable enable using System.Diagnostics; using System.Text; @@ -1691,7 +1690,7 @@ private static bool TryParseExactMultipleTimeSpan(ReadOnlySpan input, stri // one of the formats. for (int i = 0; i < formats.Length; i++) { - // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 + // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) if (formats[i] == null || formats[i]!.Length == 0) { return result.SetBadFormatSpecifierFailure(); diff --git a/src/Common/src/CoreLib/System/Globalization/UmAlQuraCalendar.cs b/src/Common/src/CoreLib/System/Globalization/UmAlQuraCalendar.cs index 49d7e893ac90..7b52e833e90a 100644 --- a/src/Common/src/CoreLib/System/Globalization/UmAlQuraCalendar.cs +++ b/src/Common/src/CoreLib/System/Globalization/UmAlQuraCalendar.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System.Globalization diff --git a/src/Common/src/CoreLib/System/Guid.Unix.cs b/src/Common/src/CoreLib/System/Guid.Unix.cs index 113f76dfe396..1c39e112ed7e 100644 --- a/src/Common/src/CoreLib/System/Guid.Unix.cs +++ b/src/Common/src/CoreLib/System/Guid.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/Guid.Windows.cs b/src/Common/src/CoreLib/System/Guid.Windows.cs index 46bdec2c0f29..6a275084f938 100644 --- a/src/Common/src/CoreLib/System/Guid.Windows.cs +++ b/src/Common/src/CoreLib/System/Guid.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { partial struct Guid diff --git a/src/Common/src/CoreLib/System/Guid.cs b/src/Common/src/CoreLib/System/Guid.cs index 6bcf48cf71c0..3f5abbb5fbc7 100644 --- a/src/Common/src/CoreLib/System/Guid.cs +++ b/src/Common/src/CoreLib/System/Guid.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; @@ -197,7 +196,7 @@ public static Guid Parse(ReadOnlySpan input) return result._parsedGuid; } - public static bool TryParse(string input, out Guid result) + public static bool TryParse(string? input, out Guid result) { if (input == null) { diff --git a/src/Common/src/CoreLib/System/HResults.cs b/src/Common/src/CoreLib/System/HResults.cs index df12ac3e4896..4da0e657a98e 100644 --- a/src/Common/src/CoreLib/System/HResults.cs +++ b/src/Common/src/CoreLib/System/HResults.cs @@ -18,7 +18,6 @@ // Reflection will use 0x1600 -> 0x161f. IO will use 0x1620 -> 0x163f. // Security will use 0x1640 -> 0x165f -#nullable enable using System; namespace System diff --git a/src/Common/src/CoreLib/System/HashCode.cs b/src/Common/src/CoreLib/System/HashCode.cs index 09fef5d95d3a..4d9dd6220575 100644 --- a/src/Common/src/CoreLib/System/HashCode.cs +++ b/src/Common/src/CoreLib/System/HashCode.cs @@ -41,7 +41,6 @@ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT */ -#nullable enable using System.Collections.Generic; using System.ComponentModel; using System.Numerics; diff --git a/src/Common/src/CoreLib/System/IAsyncDisposable.cs b/src/Common/src/CoreLib/System/IAsyncDisposable.cs index 3139b0051329..c29f549df294 100644 --- a/src/Common/src/CoreLib/System/IAsyncDisposable.cs +++ b/src/Common/src/CoreLib/System/IAsyncDisposable.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Threading.Tasks; namespace System diff --git a/src/Common/src/CoreLib/System/IAsyncResult.cs b/src/Common/src/CoreLib/System/IAsyncResult.cs index 8d7b32327e83..1caa724c8fd8 100644 --- a/src/Common/src/CoreLib/System/IAsyncResult.cs +++ b/src/Common/src/CoreLib/System/IAsyncResult.cs @@ -11,7 +11,6 @@ ** ===========================================================*/ -#nullable enable using System.Threading; namespace System diff --git a/src/Common/src/CoreLib/System/ICloneable.cs b/src/Common/src/CoreLib/System/ICloneable.cs index 325a367ba76e..9f123e45c849 100644 --- a/src/Common/src/CoreLib/System/ICloneable.cs +++ b/src/Common/src/CoreLib/System/ICloneable.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { public interface ICloneable diff --git a/src/Common/src/CoreLib/System/IComparable.cs b/src/Common/src/CoreLib/System/IComparable.cs index 1a23580e324f..c87f57253ea0 100644 --- a/src/Common/src/CoreLib/System/IComparable.cs +++ b/src/Common/src/CoreLib/System/IComparable.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable +using System.Diagnostics.CodeAnalysis; + namespace System { // The IComparable interface is implemented by classes that support an @@ -33,6 +34,6 @@ public interface IComparable // if this is equal to object, or a value greater than zero // if this is greater than object. // - int CompareTo(T other); + int CompareTo([AllowNull] T other); } } diff --git a/src/Common/src/CoreLib/System/IConvertible.cs b/src/Common/src/CoreLib/System/IConvertible.cs index 2b0c13425b3e..0acfc9c84a4b 100644 --- a/src/Common/src/CoreLib/System/IConvertible.cs +++ b/src/Common/src/CoreLib/System/IConvertible.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { // The IConvertible interface represents an object that contains a value. This diff --git a/src/Common/src/CoreLib/System/ICustomFormatter.cs b/src/Common/src/CoreLib/System/ICustomFormatter.cs index df5d9b8cf438..6911e8c56081 100644 --- a/src/Common/src/CoreLib/System/ICustomFormatter.cs +++ b/src/Common/src/CoreLib/System/ICustomFormatter.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ -#nullable enable namespace System { public interface ICustomFormatter diff --git a/src/Common/src/CoreLib/System/IDisposable.cs b/src/Common/src/CoreLib/System/IDisposable.cs index fb89476b1529..24f0740edced 100644 --- a/src/Common/src/CoreLib/System/IDisposable.cs +++ b/src/Common/src/CoreLib/System/IDisposable.cs @@ -12,7 +12,6 @@ ** ===========================================================*/ -#nullable enable namespace System { // IDisposable is an attempt at helping to solve problems with deterministic diff --git a/src/Common/src/CoreLib/System/IEquatable.cs b/src/Common/src/CoreLib/System/IEquatable.cs index 482f467f8529..1182d028531c 100644 --- a/src/Common/src/CoreLib/System/IEquatable.cs +++ b/src/Common/src/CoreLib/System/IEquatable.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable +using System.Diagnostics.CodeAnalysis; + namespace System { public interface IEquatable { - bool Equals(T other); + bool Equals([AllowNull] T other); } } diff --git a/src/Common/src/CoreLib/System/IFormatProvider.cs b/src/Common/src/CoreLib/System/IFormatProvider.cs index 706dea8cc688..f1e767f54372 100644 --- a/src/Common/src/CoreLib/System/IFormatProvider.cs +++ b/src/Common/src/CoreLib/System/IFormatProvider.cs @@ -11,7 +11,6 @@ ** ============================================================*/ -#nullable enable namespace System { public interface IFormatProvider diff --git a/src/Common/src/CoreLib/System/IFormattable.cs b/src/Common/src/CoreLib/System/IFormattable.cs index e3fa7c19f0a1..bb5aeae97aa6 100644 --- a/src/Common/src/CoreLib/System/IFormattable.cs +++ b/src/Common/src/CoreLib/System/IFormattable.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { public interface IFormattable diff --git a/src/Common/src/CoreLib/System/IO/BinaryReader.cs b/src/Common/src/CoreLib/System/IO/BinaryReader.cs index 280afe6665f4..560c998a442e 100644 --- a/src/Common/src/CoreLib/System/IO/BinaryReader.cs +++ b/src/Common/src/CoreLib/System/IO/BinaryReader.cs @@ -14,7 +14,6 @@ ** ============================================================*/ -#nullable enable using System.Buffers.Binary; using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/IO/BinaryWriter.cs b/src/Common/src/CoreLib/System/IO/BinaryWriter.cs index 89ebf98f4bd0..1e8f8bdb8cdd 100644 --- a/src/Common/src/CoreLib/System/IO/BinaryWriter.cs +++ b/src/Common/src/CoreLib/System/IO/BinaryWriter.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Text; using System.Diagnostics; using System.Buffers; diff --git a/src/Common/src/CoreLib/System/IO/DirectoryNotFoundException.cs b/src/Common/src/CoreLib/System/IO/DirectoryNotFoundException.cs index 58d4ee1a3f03..7fdf3bce29e3 100644 --- a/src/Common/src/CoreLib/System/IO/DirectoryNotFoundException.cs +++ b/src/Common/src/CoreLib/System/IO/DirectoryNotFoundException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System.IO diff --git a/src/Common/src/CoreLib/System/IO/DisableMediaInsertionPrompt.cs b/src/Common/src/CoreLib/System/IO/DisableMediaInsertionPrompt.cs index cfb4b6667a7f..a3a2d29837ca 100644 --- a/src/Common/src/CoreLib/System/IO/DisableMediaInsertionPrompt.cs +++ b/src/Common/src/CoreLib/System/IO/DisableMediaInsertionPrompt.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable #if MS_IO_REDIST using System; diff --git a/src/Common/src/CoreLib/System/IO/DriveInfoInternal.Unix.cs b/src/Common/src/CoreLib/System/IO/DriveInfoInternal.Unix.cs index c4eba1c24c5b..78ef95704fe9 100644 --- a/src/Common/src/CoreLib/System/IO/DriveInfoInternal.Unix.cs +++ b/src/Common/src/CoreLib/System/IO/DriveInfoInternal.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Text; diff --git a/src/Common/src/CoreLib/System/IO/EncodingCache.cs b/src/Common/src/CoreLib/System/IO/EncodingCache.cs index fb3795e5e266..53379bc77f38 100644 --- a/src/Common/src/CoreLib/System/IO/EncodingCache.cs +++ b/src/Common/src/CoreLib/System/IO/EncodingCache.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Text; namespace System.IO diff --git a/src/Common/src/CoreLib/System/IO/EndOfStreamException.cs b/src/Common/src/CoreLib/System/IO/EndOfStreamException.cs index 69759aac1b4e..c965b6a1c201 100644 --- a/src/Common/src/CoreLib/System/IO/EndOfStreamException.cs +++ b/src/Common/src/CoreLib/System/IO/EndOfStreamException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System.IO diff --git a/src/Common/src/CoreLib/System/IO/Error.cs b/src/Common/src/CoreLib/System/IO/Error.cs index db8095428ac8..fd39f166cf9c 100644 --- a/src/Common/src/CoreLib/System/IO/Error.cs +++ b/src/Common/src/CoreLib/System/IO/Error.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.IO { /// diff --git a/src/Common/src/CoreLib/System/IO/FileAccess.cs b/src/Common/src/CoreLib/System/IO/FileAccess.cs index 2fd7408b85f5..1b70bae17297 100644 --- a/src/Common/src/CoreLib/System/IO/FileAccess.cs +++ b/src/Common/src/CoreLib/System/IO/FileAccess.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; namespace System.IO diff --git a/src/Common/src/CoreLib/System/IO/FileLoadException.cs b/src/Common/src/CoreLib/System/IO/FileLoadException.cs index a893aca47b46..729d480d959c 100644 --- a/src/Common/src/CoreLib/System/IO/FileLoadException.cs +++ b/src/Common/src/CoreLib/System/IO/FileLoadException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System.IO diff --git a/src/Common/src/CoreLib/System/IO/FileMode.cs b/src/Common/src/CoreLib/System/IO/FileMode.cs index 39c74e50253f..77f2fe6f20fb 100644 --- a/src/Common/src/CoreLib/System/IO/FileMode.cs +++ b/src/Common/src/CoreLib/System/IO/FileMode.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.IO { // Contains constants for specifying how the OS should open a file. diff --git a/src/Common/src/CoreLib/System/IO/FileNotFoundException.cs b/src/Common/src/CoreLib/System/IO/FileNotFoundException.cs index 9ab3eb38e534..0ce1c74da349 100644 --- a/src/Common/src/CoreLib/System/IO/FileNotFoundException.cs +++ b/src/Common/src/CoreLib/System/IO/FileNotFoundException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.Serialization; diff --git a/src/Common/src/CoreLib/System/IO/FileOptions.cs b/src/Common/src/CoreLib/System/IO/FileOptions.cs index b11b9bb14017..ae8396a588f8 100644 --- a/src/Common/src/CoreLib/System/IO/FileOptions.cs +++ b/src/Common/src/CoreLib/System/IO/FileOptions.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/IO/FileShare.cs b/src/Common/src/CoreLib/System/IO/FileShare.cs index 12dc6e64ebc2..e9b9b5e32f98 100644 --- a/src/Common/src/CoreLib/System/IO/FileShare.cs +++ b/src/Common/src/CoreLib/System/IO/FileShare.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System; namespace System.IO diff --git a/src/Common/src/CoreLib/System/IO/FileStream.Linux.cs b/src/Common/src/CoreLib/System/IO/FileStream.Linux.cs index 33207fc6023e..873c4eb5599d 100644 --- a/src/Common/src/CoreLib/System/IO/FileStream.Linux.cs +++ b/src/Common/src/CoreLib/System/IO/FileStream.Linux.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Threading; diff --git a/src/Common/src/CoreLib/System/IO/FileStream.OSX.cs b/src/Common/src/CoreLib/System/IO/FileStream.OSX.cs index c8e4c9086dc4..f29e92233736 100644 --- a/src/Common/src/CoreLib/System/IO/FileStream.OSX.cs +++ b/src/Common/src/CoreLib/System/IO/FileStream.OSX.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.IO { public partial class FileStream : Stream diff --git a/src/Common/src/CoreLib/System/IO/FileStream.Unix.cs b/src/Common/src/CoreLib/System/IO/FileStream.Unix.cs index f90b53c7d9c6..59cb89030a7e 100644 --- a/src/Common/src/CoreLib/System/IO/FileStream.Unix.cs +++ b/src/Common/src/CoreLib/System/IO/FileStream.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; @@ -291,7 +290,7 @@ public override ValueTask DisposeAsync() // override may already exist on a derived type. if (_useAsyncIO && _writePos > 0) { - return new ValueTask(Task.Factory.StartNew(s => ((FileStream)s!).Dispose(), this, // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + return new ValueTask(Task.Factory.StartNew(s => ((FileStream)s!).Dispose(), this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); } @@ -365,7 +364,7 @@ private Task FlushAsyncInternal(CancellationToken cancellationToken) if (CanWrite) { return Task.Factory.StartNew( - state => ((FileStream)state!).FlushOSBuffer(), // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + state => ((FileStream)state!).FlushOSBuffer(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, @@ -569,7 +568,7 @@ private unsafe int ReadNative(Span buffer) // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); - var thisRef = (FileStream)s!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + var thisRef = (FileStream)s!; Debug.Assert(thisRef._asyncState != null); try { @@ -728,7 +727,7 @@ private ValueTask WriteAsyncInternal(ReadOnlyMemory source, CancellationTo // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); - var thisRef = (FileStream)s!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + var thisRef = (FileStream)s!; Debug.Assert(thisRef._asyncState != null); try { diff --git a/src/Common/src/CoreLib/System/IO/FileStream.Win32.cs b/src/Common/src/CoreLib/System/IO/FileStream.Win32.cs index f97f53153051..1f4f7fdb5dec 100644 --- a/src/Common/src/CoreLib/System/IO/FileStream.Win32.cs +++ b/src/Common/src/CoreLib/System/IO/FileStream.Win32.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using Microsoft.Win32.SafeHandles; diff --git a/src/Common/src/CoreLib/System/IO/FileStream.WinRT.cs b/src/Common/src/CoreLib/System/IO/FileStream.WinRT.cs index 752a6d9d8a96..6266d5dc20f9 100644 --- a/src/Common/src/CoreLib/System/IO/FileStream.WinRT.cs +++ b/src/Common/src/CoreLib/System/IO/FileStream.WinRT.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using Microsoft.Win32.SafeHandles; +using System.Diagnostics; using System.Runtime.InteropServices; namespace System.IO @@ -33,6 +33,7 @@ private unsafe SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOpt using (DisableMediaInsertionPrompt.Create()) { + Debug.Assert(_path != null); return ValidateFileHandle(Interop.Kernel32.CreateFile2( lpFileName: _path, dwDesiredAccess: access, diff --git a/src/Common/src/CoreLib/System/IO/FileStream.Windows.cs b/src/Common/src/CoreLib/System/IO/FileStream.Windows.cs index 49e9812e0ae1..be48833ceb49 100644 --- a/src/Common/src/CoreLib/System/IO/FileStream.Windows.cs +++ b/src/Common/src/CoreLib/System/IO/FileStream.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; @@ -1588,7 +1587,7 @@ private Task FlushAsyncInternal(CancellationToken cancellationToken) if (CanWrite) { return Task.Factory.StartNew( - state => ((FileStream)state!).FlushOSBuffer(), // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + state => ((FileStream)state!).FlushOSBuffer(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, diff --git a/src/Common/src/CoreLib/System/IO/FileStream.cs b/src/Common/src/CoreLib/System/IO/FileStream.cs index 0f75f369488b..4f4198330c20 100644 --- a/src/Common/src/CoreLib/System/IO/FileStream.cs +++ b/src/Common/src/CoreLib/System/IO/FileStream.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; diff --git a/src/Common/src/CoreLib/System/IO/FileStreamCompletionSource.Win32.cs b/src/Common/src/CoreLib/System/IO/FileStreamCompletionSource.Win32.cs index a1ad6291f736..837946e04f7d 100644 --- a/src/Common/src/CoreLib/System/IO/FileStreamCompletionSource.Win32.cs +++ b/src/Common/src/CoreLib/System/IO/FileStreamCompletionSource.Win32.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/IO/IOException.cs b/src/Common/src/CoreLib/System/IO/IOException.cs index ba8525f043c1..a22cc3bc48f8 100644 --- a/src/Common/src/CoreLib/System/IO/IOException.cs +++ b/src/Common/src/CoreLib/System/IO/IOException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System.IO diff --git a/src/Common/src/CoreLib/System/IO/MemoryStream.cs b/src/Common/src/CoreLib/System/IO/MemoryStream.cs index 7377271315c9..11a41f78393d 100644 --- a/src/Common/src/CoreLib/System/IO/MemoryStream.cs +++ b/src/Common/src/CoreLib/System/IO/MemoryStream.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -452,7 +451,7 @@ public override ValueTask ReadAsync(Memory buffer, CancellationToken // it then fall back to doing the ArrayPool/copy behavior. return new ValueTask( MemoryMarshal.TryGetArray(buffer, out ArraySegment destinationArray) ? - Read(destinationArray.Array!, destinationArray.Offset, destinationArray.Count) : // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + Read(destinationArray.Array!, destinationArray.Offset, destinationArray.Count) : Read(buffer.Span)); } catch (OperationCanceledException oce) @@ -767,7 +766,7 @@ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationTo // Unlike ReadAsync, we could delegate to WriteAsync(byte[], ...) here, but we don't for consistency. if (MemoryMarshal.TryGetArray(buffer, out ArraySegment sourceArray)) { - Write(sourceArray.Array!, sourceArray.Offset, sourceArray.Count); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + Write(sourceArray.Array!, sourceArray.Offset, sourceArray.Count); } else { diff --git a/src/Common/src/CoreLib/System/IO/Path.Unix.cs b/src/Common/src/CoreLib/System/IO/Path.Unix.cs index f8c93d65160d..5bc727f45029 100644 --- a/src/Common/src/CoreLib/System/IO/Path.Unix.cs +++ b/src/Common/src/CoreLib/System/IO/Path.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; diff --git a/src/Common/src/CoreLib/System/IO/Path.cs b/src/Common/src/CoreLib/System/IO/Path.cs index db491bfdc00f..b0c3df34160d 100644 --- a/src/Common/src/CoreLib/System/IO/Path.cs +++ b/src/Common/src/CoreLib/System/IO/Path.cs @@ -4,6 +4,7 @@ #nullable enable using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Text; @@ -46,7 +47,8 @@ public static partial class Path // returns null. If path does not contain a file extension, // the new file extension is appended to the path. If extension // is null, any existing extension is removed from path. - public static string? ChangeExtension(string? path, string? extension) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + [return: NotNullIfNotNull("path")] + public static string? ChangeExtension(string? path, string? extension) { if (path == null) return null; @@ -99,7 +101,7 @@ public static partial class Path /// /// Directory separators are normalized in the returned string. /// - public static string? GetDirectoryName(string? path) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + public static string? GetDirectoryName(string? path) { if (path == null || PathInternal.IsEffectivelyEmpty(path.AsSpan())) return null; @@ -147,7 +149,8 @@ private static int GetDirectoryNameOffset(ReadOnlySpan path) /// The returned value is null if the given path is null or empty if the given path does not include an /// extension. /// - public static string? GetExtension(string? path) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + [return: NotNullIfNotNull("path")] + public static string? GetExtension(string? path) { if (path == null) return null; @@ -186,6 +189,7 @@ public static ReadOnlySpan GetExtension(ReadOnlySpan path) /// the characters of path that follow the last separator in path. The resulting string is /// null if path is null. /// + [return: NotNullIfNotNull("path")] public static string? GetFileName(string? path) { if (path == null) @@ -217,7 +221,8 @@ public static ReadOnlySpan GetFileName(ReadOnlySpan path) return path; } - public static string? GetFileNameWithoutExtension(string? path) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + [return: NotNullIfNotNull("path")] + public static string? GetFileNameWithoutExtension(string? path) { if (path == null) return null; @@ -346,7 +351,7 @@ public static string Combine(params string[] paths) throw new ArgumentNullException(nameof(paths)); } - int finalSize = 0; + int maxSize = 0; int firstComponent = 0; // We have two passes, the first calculates how large a buffer to allocate and does some precondition @@ -367,19 +372,21 @@ public static string Combine(params string[] paths) if (IsPathRooted(paths[i])) { firstComponent = i; - finalSize = paths[i].Length; + maxSize = paths[i].Length; } else { - finalSize += paths[i].Length; + maxSize += paths[i].Length; } char ch = paths[i][paths[i].Length - 1]; if (!PathInternal.IsDirectorySeparator(ch)) - finalSize++; + maxSize++; } - StringBuilder finalPath = StringBuilderCache.Acquire(finalSize); + Span initialBuffer = stackalloc char[260]; // MaxShortPath on Windows + var builder = new ValueStringBuilder(initialBuffer); + builder.EnsureCapacity(maxSize); for (int i = firstComponent; i < paths.Length; i++) { @@ -388,23 +395,23 @@ public static string Combine(params string[] paths) continue; } - if (finalPath.Length == 0) + if (builder.Length == 0) { - finalPath.Append(paths[i]); + builder.Append(paths[i]); } else { - char ch = finalPath[finalPath.Length - 1]; + char ch = builder[builder.Length - 1]; if (!PathInternal.IsDirectorySeparator(ch)) { - finalPath.Append(PathInternal.DirectorySeparatorChar); + builder.Append(PathInternal.DirectorySeparatorChar); } - finalPath.Append(paths[i]); + builder.Append(paths[i]); } } - return StringBuilderCache.GetStringAndRelease(finalPath); + return builder.ToString(); } // Unlike Combine(), Join() methods do not consider rooting. They simply combine paths, ensuring that there @@ -434,6 +441,23 @@ public static string Join(ReadOnlySpan path1, ReadOnlySpan path2, Re return JoinInternal(path1, path2, path3); } + public static string Join(ReadOnlySpan path1, ReadOnlySpan path2, ReadOnlySpan path3, ReadOnlySpan path4) + { + if (path1.Length == 0) + return Join(path2, path3, path4); + + if (path2.Length == 0) + return Join(path1, path3, path4); + + if (path3.Length == 0) + return Join(path1, path2, path4); + + if (path4.Length == 0) + return Join(path1, path2, path3); + + return JoinInternal(path1, path2, path3, path4); + } + public static string Join(string? path1, string? path2) { return Join(path1.AsSpan(), path2.AsSpan()); @@ -444,6 +468,60 @@ public static string Join(string? path1, string? path2, string? path3) return Join(path1.AsSpan(), path2.AsSpan(), path3.AsSpan()); } + public static string Join(string? path1, string? path2, string? path3, string? path4) + { + return Join(path1.AsSpan(), path2.AsSpan(), path3.AsSpan(), path4.AsSpan()); + } + + public static string Join(params string?[] paths) + { + if (paths == null) + { + throw new ArgumentNullException(nameof(paths)); + } + + if (paths.Length == 0) + { + return string.Empty; + } + + int maxSize = 0; + foreach (string? path in paths) + { + maxSize += path?.Length ?? 0; + } + maxSize += paths.Length - 1; + + Span initialBuffer = stackalloc char[260]; // MaxShortPath on Windows + var builder = new ValueStringBuilder(initialBuffer); + builder.EnsureCapacity(maxSize); + + for (int i = 0; i < paths.Length; i++) + { + string? path = paths[i]; + if (path == null || path.Length == 0) + { + continue; + } + + if (builder.Length == 0) + { + builder.Append(path); + } + else + { + if (!PathInternal.IsDirectorySeparator(builder[builder.Length - 1]) && !PathInternal.IsDirectorySeparator(path[0])) + { + builder.Append(PathInternal.DirectorySeparatorChar); + } + + builder.Append(path); + } + } + + return builder.ToString(); + } + public static bool TryJoin(ReadOnlySpan path1, ReadOnlySpan path2, Span destination, out int charsWritten) { charsWritten = 0; diff --git a/src/Common/src/CoreLib/System/IO/PathHelper.Windows.cs b/src/Common/src/CoreLib/System/IO/PathHelper.Windows.cs index f494412a52f2..83618cfa13c0 100644 --- a/src/Common/src/CoreLib/System/IO/PathHelper.Windows.cs +++ b/src/Common/src/CoreLib/System/IO/PathHelper.Windows.cs @@ -130,7 +130,7 @@ internal static int PrependDevicePathChars(ref ValueStringBuilder content, bool internal static string TryExpandShortFileName(ref ValueStringBuilder outputBuilder, string? originalPath) { // We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To - // avoid allocating like crazy we'll create only one input array and modify the contents with embedded nulls. + // avoid allocating a lot we'll create only one input array and modify the contents with embedded nulls. Debug.Assert(!PathInternal.IsPartiallyQualified(outputBuilder.AsSpan()), "should have resolved by now"); diff --git a/src/Common/src/CoreLib/System/IO/PathInternal.Windows.cs b/src/Common/src/CoreLib/System/IO/PathInternal.Windows.cs index 40ed96f63c3a..82474656e4e5 100644 --- a/src/Common/src/CoreLib/System/IO/PathInternal.Windows.cs +++ b/src/Common/src/CoreLib/System/IO/PathInternal.Windows.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. #nullable enable +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Text; @@ -87,6 +88,7 @@ internal static bool EndsWithPeriodOrSpace(string? path) /// away from paths during normalization, but if we see such a path at this point it should be /// normalized and has retained the final characters. (Typically from one of the *Info classes) /// + [return: NotNullIfNotNull("path")] internal static string? EnsureExtendedPrefixIfNeeded(string? path) { if (path != null && (path.Length >= MaxShortPath || EndsWithPeriodOrSpace(path))) diff --git a/src/Common/src/CoreLib/System/IO/PathInternal.cs b/src/Common/src/CoreLib/System/IO/PathInternal.cs index 549a2d18b29e..c6e1de46c8d7 100644 --- a/src/Common/src/CoreLib/System/IO/PathInternal.cs +++ b/src/Common/src/CoreLib/System/IO/PathInternal.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Text; diff --git a/src/Common/src/CoreLib/System/IO/PathTooLongException.cs b/src/Common/src/CoreLib/System/IO/PathTooLongException.cs index e0a35f7c9ee1..3a69930a911f 100644 --- a/src/Common/src/CoreLib/System/IO/PathTooLongException.cs +++ b/src/Common/src/CoreLib/System/IO/PathTooLongException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System.IO diff --git a/src/Common/src/CoreLib/System/IO/PersistedFiles.Names.Unix.cs b/src/Common/src/CoreLib/System/IO/PersistedFiles.Names.Unix.cs index 03bfc0251009..8984f1aee32b 100644 --- a/src/Common/src/CoreLib/System/IO/PersistedFiles.Names.Unix.cs +++ b/src/Common/src/CoreLib/System/IO/PersistedFiles.Names.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.IO { internal static partial class PersistedFiles diff --git a/src/Common/src/CoreLib/System/IO/PinnedBufferMemoryStream.cs b/src/Common/src/CoreLib/System/IO/PinnedBufferMemoryStream.cs index 7c636b952728..bcec1f33ac9f 100644 --- a/src/Common/src/CoreLib/System/IO/PinnedBufferMemoryStream.cs +++ b/src/Common/src/CoreLib/System/IO/PinnedBufferMemoryStream.cs @@ -14,7 +14,6 @@ ** ===========================================================*/ -#nullable enable using System; using System.Runtime.InteropServices; using System.Diagnostics; @@ -39,9 +38,11 @@ internal PinnedBufferMemoryStream(byte[] array) Initialize(ptr, len, len, FileAccess.Read); } +#if !netstandard public override int Read(Span buffer) => ReadCore(buffer); public override void Write(ReadOnlySpan buffer) => WriteCore(buffer); +#endif ~PinnedBufferMemoryStream() { diff --git a/src/Common/src/CoreLib/System/IO/SeekOrigin.cs b/src/Common/src/CoreLib/System/IO/SeekOrigin.cs index e1da4d5853d3..3798a0ce7022 100644 --- a/src/Common/src/CoreLib/System/IO/SeekOrigin.cs +++ b/src/Common/src/CoreLib/System/IO/SeekOrigin.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.IO { // Provides seek reference points. To seek to the end of a stream, diff --git a/src/Common/src/CoreLib/System/IO/Stream.cs b/src/Common/src/CoreLib/System/IO/Stream.cs index 55ae9007c8b4..51cc816a8597 100644 --- a/src/Common/src/CoreLib/System/IO/Stream.cs +++ b/src/Common/src/CoreLib/System/IO/Stream.cs @@ -15,7 +15,6 @@ ** ===========================================================*/ -#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.ExceptionServices; @@ -43,7 +42,11 @@ internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() { // Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's // WaitHandle, we don't need to worry about Disposing it. - return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore!, () => new SemaphoreSlim(1, 1)); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 +#pragma warning disable CS8634 // TODO-NULLABLE: Remove warning disable when nullable attributes are respected +#pragma warning disable CS8603 // TODO-NULLABLE: Remove warning disable when nullable attributes are respected + return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); +#pragma warning restore CS8603 +#pragma warning restore CS8634 } public abstract bool CanRead @@ -256,7 +259,7 @@ public Task FlushAsync() public virtual Task FlushAsync(CancellationToken cancellationToken) { - return Task.Factory.StartNew(state => ((Stream)state!).Flush(), this, // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + return Task.Factory.StartNew(state => ((Stream)state!).Flush(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } @@ -381,7 +384,7 @@ public virtual ValueTask ReadAsync(Memory buffer, CancellationToken c { if (MemoryMarshal.TryGetArray(buffer, out ArraySegment array)) { - return new ValueTask(ReadAsync(array.Array!, array.Offset, array.Count, cancellationToken)); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + return new ValueTask(ReadAsync(array.Array!, array.Offset, array.Count, cancellationToken)); } else { @@ -512,7 +515,7 @@ private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWrite asyncWaiter.ContinueWith((t, state) => { Debug.Assert(t.IsCompletedSuccessfully, "The semaphore wait should always complete successfully."); - var rwt = (ReadWriteTask)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + var rwt = (ReadWriteTask)state!; Debug.Assert(rwt._stream != null); rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask); }, readWriteTask, default, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); @@ -692,7 +695,7 @@ public virtual ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationTok { if (MemoryMarshal.TryGetArray(buffer, out ArraySegment array)) { - return new ValueTask(WriteAsync(array.Array!, array.Offset, array.Count, cancellationToken)); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + return new ValueTask(WriteAsync(array.Array!, array.Offset, array.Count, cancellationToken)); } else { @@ -1062,7 +1065,7 @@ public WaitHandle AsyncWaitHandle { get { - return LazyInitializer.EnsureInitialized(ref _waitHandle!, () => new ManualResetEvent(true)); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + return LazyInitializer.EnsureInitialized(ref _waitHandle!, () => new ManualResetEvent(true)); // Remove ! when nullable attributes are respected } } diff --git a/src/Common/src/CoreLib/System/IO/StreamHelpers.CopyValidation.cs b/src/Common/src/CoreLib/System/IO/StreamHelpers.CopyValidation.cs index fe849fbef202..45bbd816df01 100644 --- a/src/Common/src/CoreLib/System/IO/StreamHelpers.CopyValidation.cs +++ b/src/Common/src/CoreLib/System/IO/StreamHelpers.CopyValidation.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.IO { /// Provides methods to help in the implementation of Stream-derived types. diff --git a/src/Common/src/CoreLib/System/IO/StreamReader.cs b/src/Common/src/CoreLib/System/IO/StreamReader.cs index 9d836c0b98b2..0ebcede1e026 100644 --- a/src/Common/src/CoreLib/System/IO/StreamReader.cs +++ b/src/Common/src/CoreLib/System/IO/StreamReader.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; @@ -85,6 +84,7 @@ private void CheckAsyncTaskInProgress() } } + [DoesNotReturn] private static void ThrowAsyncIOInProgress() => throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress); @@ -135,17 +135,25 @@ public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByt { } - public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen) + public StreamReader(Stream stream, Encoding? encoding = null, bool detectEncodingFromByteOrderMarks = true, int bufferSize = -1, bool leaveOpen = false) { - if (stream == null || encoding == null) + if (stream == null) { - throw new ArgumentNullException(stream == null ? nameof(stream) : nameof(encoding)); + throw new ArgumentNullException(nameof(stream)); + } + if (encoding == null) + { + encoding = Encoding.UTF8; } if (!stream.CanRead) { throw new ArgumentException(SR.Argument_StreamNotReadable); } - if (bufferSize <= 0) + if (bufferSize == -1) + { + bufferSize = DefaultBufferSize; + } + else if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); } diff --git a/src/Common/src/CoreLib/System/IO/StreamWriter.cs b/src/Common/src/CoreLib/System/IO/StreamWriter.cs index 3a999195bc1d..9d143ed1786a 100644 --- a/src/Common/src/CoreLib/System/IO/StreamWriter.cs +++ b/src/Common/src/CoreLib/System/IO/StreamWriter.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; @@ -57,6 +57,7 @@ private void CheckAsyncTaskInProgress() } } + [DoesNotReturn] private static void ThrowAsyncIOInProgress() => throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress); @@ -90,18 +91,26 @@ public StreamWriter(Stream stream, Encoding encoding, int bufferSize) { } - public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen) + public StreamWriter(Stream stream, Encoding? encoding = null, int bufferSize = -1, bool leaveOpen = false) : base(null) // Ask for CurrentCulture all the time { - if (stream == null || encoding == null) + if (stream == null) { - throw new ArgumentNullException(stream == null ? nameof(stream) : nameof(encoding)); + throw new ArgumentNullException(nameof(stream)); + } + if (encoding == null) + { + encoding = UTF8NoBOM; } if (!stream.CanWrite) { throw new ArgumentException(SR.Argument_StreamNotWritable); } - if (bufferSize <= 0) + if (bufferSize == -1) + { + bufferSize = DefaultBufferSize; + } + else if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); } diff --git a/src/Common/src/CoreLib/System/IO/TextReader.cs b/src/Common/src/CoreLib/System/IO/TextReader.cs index e2f0af91788d..5afc919095d4 100644 --- a/src/Common/src/CoreLib/System/IO/TextReader.cs +++ b/src/Common/src/CoreLib/System/IO/TextReader.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Text; using System.Threading; using System.Threading.Tasks; @@ -210,7 +209,7 @@ public virtual int ReadBlock(Span buffer) { return Task.Factory.StartNew(state => { - return ((TextReader)state!).ReadLine(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + return ((TextReader)state!).ReadLine(); }, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } @@ -254,10 +253,10 @@ public virtual Task ReadAsync(char[] buffer, int index, int count) public virtual ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => new ValueTask(MemoryMarshal.TryGetArray(buffer, out ArraySegment array) ? - ReadAsync(array.Array!, array.Offset, array.Count) : // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + ReadAsync(array.Array!, array.Offset, array.Count) : Task.Factory.StartNew(state => { - var t = (Tuple>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + var t = (Tuple>)state!; return t.Item1.Read(t.Item2.Span); }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); @@ -266,7 +265,7 @@ internal virtual ValueTask ReadAsyncInternal(Memory buffer, Cancellat var tuple = new Tuple>(this, buffer); return new ValueTask(Task.Factory.StartNew(state => { - var t = (Tuple>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + var t = (Tuple>)state!; return t.Item1.Read(t.Item2.Span); }, tuple, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); @@ -292,10 +291,10 @@ public virtual Task ReadBlockAsync(char[] buffer, int index, int count) public virtual ValueTask ReadBlockAsync(Memory buffer, CancellationToken cancellationToken = default) => new ValueTask(MemoryMarshal.TryGetArray(buffer, out ArraySegment array) ? - ReadBlockAsync(array.Array!, array.Offset, array.Count) : // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + ReadBlockAsync(array.Array!, array.Offset, array.Count) : Task.Factory.StartNew(state => { - var t = (Tuple>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + var t = (Tuple>)state!; return t.Item1.ReadBlock(t.Item2.Span); }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); diff --git a/src/Common/src/CoreLib/System/IO/TextWriter.cs b/src/Common/src/CoreLib/System/IO/TextWriter.cs index f648df0ce60d..9dfb1405a943 100644 --- a/src/Common/src/CoreLib/System/IO/TextWriter.cs +++ b/src/Common/src/CoreLib/System/IO/TextWriter.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Text; using System.Threading; using System.Globalization; @@ -10,6 +9,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Buffers; +using System.Diagnostics.CodeAnalysis; namespace System.IO { @@ -118,7 +118,8 @@ public abstract Encoding Encoding /// the TextWriter to be readable by a TextReader, only one of the following line /// terminator strings should be used: "\r", "\n", or "\r\n". /// - public virtual string? NewLine // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/2384 + [AllowNull] + public virtual string NewLine { get { return CoreNewLineStr; } set @@ -306,7 +307,7 @@ public virtual void Write(StringBuilder? value) if (value != null) { foreach (ReadOnlyMemory chunk in value.GetChunks()) - Write(chunk); + Write(chunk.Span); } } @@ -546,7 +547,7 @@ public virtual Task WriteAsync(char value) var tuple = new Tuple(this, value); return Task.Factory.StartNew(state => { - var t = (Tuple)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + var t = (Tuple)state!; t.Item1.Write(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); @@ -557,7 +558,7 @@ public virtual Task WriteAsync(string? value) var tuple = new Tuple(this, value); return Task.Factory.StartNew(state => { - var t = (Tuple)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + var t = (Tuple)state!; t.Item1.Write(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); @@ -599,7 +600,7 @@ public virtual Task WriteAsync(char[] buffer, int index, int count) var tuple = new Tuple(this, buffer, index, count); return Task.Factory.StartNew(state => { - var t = (Tuple)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + var t = (Tuple)state!; t.Item1.Write(t.Item2, t.Item3, t.Item4); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); @@ -607,11 +608,11 @@ public virtual Task WriteAsync(char[] buffer, int index, int count) public virtual Task WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : - MemoryMarshal.TryGetArray(buffer, out ArraySegment array) ? // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + MemoryMarshal.TryGetArray(buffer, out ArraySegment array) ? WriteAsync(array.Array!, array.Offset, array.Count) : Task.Factory.StartNew(state => { - var t = (Tuple>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + var t = (Tuple>)state!; t.Item1.Write(t.Item2.Span); }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); @@ -620,7 +621,7 @@ public virtual Task WriteLineAsync(char value) var tuple = new Tuple(this, value); return Task.Factory.StartNew(state => { - var t = (Tuple)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + var t = (Tuple)state!; t.Item1.WriteLine(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); @@ -631,7 +632,7 @@ public virtual Task WriteLineAsync(string? value) var tuple = new Tuple(this, value); return Task.Factory.StartNew(state => { - var t = (Tuple)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + var t = (Tuple)state!; t.Item1.WriteLine(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); @@ -674,7 +675,7 @@ public virtual Task WriteLineAsync(char[] buffer, int index, int count) var tuple = new Tuple(this, buffer, index, count); return Task.Factory.StartNew(state => { - var t = (Tuple)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + var t = (Tuple)state!; t.Item1.WriteLine(t.Item2, t.Item3, t.Item4); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); @@ -682,11 +683,11 @@ public virtual Task WriteLineAsync(char[] buffer, int index, int count) public virtual Task WriteLineAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : - MemoryMarshal.TryGetArray(buffer, out ArraySegment array) ? // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + MemoryMarshal.TryGetArray(buffer, out ArraySegment array) ? WriteLineAsync(array.Array!, array.Offset, array.Count) : Task.Factory.StartNew(state => { - var t = (Tuple>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + var t = (Tuple>)state!; t.Item1.WriteLine(t.Item2.Span); }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); @@ -699,7 +700,7 @@ public virtual Task FlushAsync() { return Task.Factory.StartNew(state => { - ((TextWriter)state!).Flush(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + ((TextWriter)state!).Flush(); }, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } @@ -767,7 +768,8 @@ internal SyncTextWriter(TextWriter t) : base(t.FormatProvider) public override IFormatProvider FormatProvider => _out.FormatProvider; - public override string? NewLine + [AllowNull] + public override string NewLine { [MethodImpl(MethodImplOptions.Synchronized)] get { return _out.NewLine; } diff --git a/src/Common/src/CoreLib/System/IO/UnmanagedMemoryAccessor.cs b/src/Common/src/CoreLib/System/IO/UnmanagedMemoryAccessor.cs index 4e66b7cdec12..c9f43698705b 100644 --- a/src/Common/src/CoreLib/System/IO/UnmanagedMemoryAccessor.cs +++ b/src/Common/src/CoreLib/System/IO/UnmanagedMemoryAccessor.cs @@ -13,7 +13,6 @@ ** ===========================================================*/ -#nullable enable using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/IO/UnmanagedMemoryStream.cs b/src/Common/src/CoreLib/System/IO/UnmanagedMemoryStream.cs index a42cdf918ced..e6f67bc0393e 100644 --- a/src/Common/src/CoreLib/System/IO/UnmanagedMemoryStream.cs +++ b/src/Common/src/CoreLib/System/IO/UnmanagedMemoryStream.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -512,7 +511,7 @@ public override ValueTask ReadAsync(Memory buffer, CancellationToken // it then fall back to doing the ArrayPool/copy behavior. return new ValueTask( MemoryMarshal.TryGetArray(buffer, out ArraySegment destinationArray) ? - Read(destinationArray.Array!, destinationArray.Offset, destinationArray.Count) : // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + Read(destinationArray.Array!, destinationArray.Offset, destinationArray.Count) : Read(buffer.Span)); } catch (Exception ex) @@ -797,7 +796,7 @@ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationTo // Unlike ReadAsync, we could delegate to WriteAsync(byte[], ...) here, but we don't for consistency. if (MemoryMarshal.TryGetArray(buffer, out ArraySegment sourceArray)) { - Write(sourceArray.Array!, sourceArray.Offset, sourceArray.Count); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + Write(sourceArray.Array!, sourceArray.Offset, sourceArray.Count); } else { diff --git a/src/Common/src/CoreLib/System/IO/UnmanagedMemoryStreamWrapper.cs b/src/Common/src/CoreLib/System/IO/UnmanagedMemoryStreamWrapper.cs index d4a5f98255f7..a8c84da7adbf 100644 --- a/src/Common/src/CoreLib/System/IO/UnmanagedMemoryStreamWrapper.cs +++ b/src/Common/src/CoreLib/System/IO/UnmanagedMemoryStreamWrapper.cs @@ -11,7 +11,6 @@ ** ===========================================================*/ -#nullable enable using System.Threading; using System.Threading.Tasks; diff --git a/src/Common/src/CoreLib/System/IObservable.cs b/src/Common/src/CoreLib/System/IObservable.cs index c451a7b8ea26..aabb0b8fb426 100644 --- a/src/Common/src/CoreLib/System/IObservable.cs +++ b/src/Common/src/CoreLib/System/IObservable.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { public interface IObservable diff --git a/src/Common/src/CoreLib/System/IObserver.cs b/src/Common/src/CoreLib/System/IObserver.cs index 35906682b320..39e123de8dbf 100644 --- a/src/Common/src/CoreLib/System/IObserver.cs +++ b/src/Common/src/CoreLib/System/IObserver.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { public interface IObserver diff --git a/src/Common/src/CoreLib/System/IProgress.cs b/src/Common/src/CoreLib/System/IProgress.cs index e344c73afe28..724c7bdce9ae 100644 --- a/src/Common/src/CoreLib/System/IProgress.cs +++ b/src/Common/src/CoreLib/System/IProgress.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { /// Defines a provider for progress updates. diff --git a/src/Common/src/CoreLib/System/ISpanFormattable.cs b/src/Common/src/CoreLib/System/ISpanFormattable.cs index d63e6ff8af21..d3744addcbdb 100644 --- a/src/Common/src/CoreLib/System/ISpanFormattable.cs +++ b/src/Common/src/CoreLib/System/ISpanFormattable.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { internal interface ISpanFormattable diff --git a/src/Common/src/CoreLib/System/Index.cs b/src/Common/src/CoreLib/System/Index.cs index 9ed7ed1127be..0e4d8514dee0 100644 --- a/src/Common/src/CoreLib/System/Index.cs +++ b/src/Common/src/CoreLib/System/Index.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/IndexOutOfRangeException.cs b/src/Common/src/CoreLib/System/IndexOutOfRangeException.cs index 46d8e3869ef8..ec4195c23fbf 100644 --- a/src/Common/src/CoreLib/System/IndexOutOfRangeException.cs +++ b/src/Common/src/CoreLib/System/IndexOutOfRangeException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/InsufficientExecutionStackException.cs b/src/Common/src/CoreLib/System/InsufficientExecutionStackException.cs index e6b71b9ac29b..bb60d533f0ae 100644 --- a/src/Common/src/CoreLib/System/InsufficientExecutionStackException.cs +++ b/src/Common/src/CoreLib/System/InsufficientExecutionStackException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/InsufficientMemoryException.cs b/src/Common/src/CoreLib/System/InsufficientMemoryException.cs index 197bd166d556..b42f8c4ff998 100644 --- a/src/Common/src/CoreLib/System/InsufficientMemoryException.cs +++ b/src/Common/src/CoreLib/System/InsufficientMemoryException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/Int16.cs b/src/Common/src/CoreLib/System/Int16.cs index e67225374f12..ed556eede405 100644 --- a/src/Common/src/CoreLib/System/Int16.cs +++ b/src/Common/src/CoreLib/System/Int16.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/Int32.cs b/src/Common/src/CoreLib/System/Int32.cs index 8fe2c96394da..daf1af53f1d3 100644 --- a/src/Common/src/CoreLib/System/Int32.cs +++ b/src/Common/src/CoreLib/System/Int32.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/Int64.cs b/src/Common/src/CoreLib/System/Int64.cs index 303e69b26dd2..c61a2f76ef36 100644 --- a/src/Common/src/CoreLib/System/Int64.cs +++ b/src/Common/src/CoreLib/System/Int64.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/IntPtr.cs b/src/Common/src/CoreLib/System/IntPtr.cs index 1aedd04bbe62..ee9da7ae7852 100644 --- a/src/Common/src/CoreLib/System/IntPtr.cs +++ b/src/Common/src/CoreLib/System/IntPtr.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Serialization; diff --git a/src/Common/src/CoreLib/System/InvalidCastException.cs b/src/Common/src/CoreLib/System/InvalidCastException.cs index 11c98ec05b39..c3b22167b1e6 100644 --- a/src/Common/src/CoreLib/System/InvalidCastException.cs +++ b/src/Common/src/CoreLib/System/InvalidCastException.cs @@ -8,7 +8,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/InvalidOperationException.cs b/src/Common/src/CoreLib/System/InvalidOperationException.cs index aec2b07b5ec6..ac24a834ef57 100644 --- a/src/Common/src/CoreLib/System/InvalidOperationException.cs +++ b/src/Common/src/CoreLib/System/InvalidOperationException.cs @@ -12,7 +12,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/InvalidProgramException.cs b/src/Common/src/CoreLib/System/InvalidProgramException.cs index 63f1bfee868c..236768e25ac7 100644 --- a/src/Common/src/CoreLib/System/InvalidProgramException.cs +++ b/src/Common/src/CoreLib/System/InvalidProgramException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/InvalidTimeZoneException.cs b/src/Common/src/CoreLib/System/InvalidTimeZoneException.cs index cbf73c61eda0..165c25b15a21 100644 --- a/src/Common/src/CoreLib/System/InvalidTimeZoneException.cs +++ b/src/Common/src/CoreLib/System/InvalidTimeZoneException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/Lazy.cs b/src/Common/src/CoreLib/System/Lazy.cs index d8e9a155fd5b..b341136e8af5 100644 --- a/src/Common/src/CoreLib/System/Lazy.cs +++ b/src/Common/src/CoreLib/System/Lazy.cs @@ -10,8 +10,8 @@ // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -#nullable enable using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Runtime.ExceptionServices; using System.Threading; @@ -88,6 +88,7 @@ internal LazyHelper(LazyThreadSafetyMode mode, Exception exception) _exceptionDispatch = ExceptionDispatchInfo.Capture(exception); } + [DoesNotReturn] internal void ThrowException() { Debug.Assert(_exceptionDispatch != null, "execution path is invalid"); @@ -193,7 +194,7 @@ public class Lazy private Func? _factory; // _value eventually stores the lazily created value. It is valid when _state = null. - private T _value = default!; // TODO-NULLABLE-GENERIC + private T _value = default!; /// /// Initializes a new instance of the class that @@ -445,13 +446,14 @@ private T CreateValue() } /// Gets the value of the Lazy<T> for debugging display purposes. + [MaybeNull] internal T ValueForDebugDisplay { get { if (!IsValueCreated) { - return default!; // TODO-NULLABLE-GENERIC + return default!; } return _value; } diff --git a/src/Common/src/CoreLib/System/LocalAppContextSwitches.Common.cs b/src/Common/src/CoreLib/System/LocalAppContextSwitches.Common.cs index a7c2436c6e88..e383092d0613 100644 --- a/src/Common/src/CoreLib/System/LocalAppContextSwitches.Common.cs +++ b/src/Common/src/CoreLib/System/LocalAppContextSwitches.Common.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; namespace System diff --git a/src/Common/src/CoreLib/System/LocalAppContextSwitches.cs b/src/Common/src/CoreLib/System/LocalAppContextSwitches.cs index b63a98024970..a28535967593 100644 --- a/src/Common/src/CoreLib/System/LocalAppContextSwitches.cs +++ b/src/Common/src/CoreLib/System/LocalAppContextSwitches.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; namespace System diff --git a/src/Common/src/CoreLib/System/LocalDataStoreSlot.cs b/src/Common/src/CoreLib/System/LocalDataStoreSlot.cs index 616967c9460b..41e384e90b22 100644 --- a/src/Common/src/CoreLib/System/LocalDataStoreSlot.cs +++ b/src/Common/src/CoreLib/System/LocalDataStoreSlot.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Threading; namespace System diff --git a/src/Common/src/CoreLib/System/MarshalByRefObject.cs b/src/Common/src/CoreLib/System/MarshalByRefObject.cs index 9ef86b4124e4..a083c97c9d75 100644 --- a/src/Common/src/CoreLib/System/MarshalByRefObject.cs +++ b/src/Common/src/CoreLib/System/MarshalByRefObject.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.InteropServices; namespace System diff --git a/src/Common/src/CoreLib/System/Marvin.OrdinalIgnoreCase.cs b/src/Common/src/CoreLib/System/Marvin.OrdinalIgnoreCase.cs index 9a8f0ae9e494..71f10b5e9786 100644 --- a/src/Common/src/CoreLib/System/Marvin.OrdinalIgnoreCase.cs +++ b/src/Common/src/CoreLib/System/Marvin.OrdinalIgnoreCase.cs @@ -2,11 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; -using System.Text; +using System.Text.Unicode; using Internal.Runtime.CompilerServices; #if BIT64 diff --git a/src/Common/src/CoreLib/System/Marvin.cs b/src/Common/src/CoreLib/System/Marvin.cs index c03ede43fbd9..832c84ba82dc 100644 --- a/src/Common/src/CoreLib/System/Marvin.cs +++ b/src/Common/src/CoreLib/System/Marvin.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/Math.cs b/src/Common/src/CoreLib/System/Math.cs index ca448d0059eb..014589c48b5c 100644 --- a/src/Common/src/CoreLib/System/Math.cs +++ b/src/Common/src/CoreLib/System/Math.cs @@ -13,8 +13,8 @@ //This class contains only static members and doesn't require serialization. -#nullable enable using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Versioning; @@ -100,6 +100,7 @@ public static decimal Abs(decimal value) return decimal.Abs(value); } + [DoesNotReturn] [StackTraceHidden] private static void ThrowAbsOverflow() { @@ -539,31 +540,23 @@ public static decimal Max(decimal val1, decimal val2) public static double Max(double val1, double val2) { - // When val1 and val2 are both finite or infinite, return the larger - // * We count +0.0 as larger than -0.0 to match MSVC - // When val1 or val2, but not both, are NaN return the opposite - // * We return the opposite if either is NaN to match MSVC + // This matches the IEEE 754:2019 `maximum` function + // + // It propagates NaN inputs back to the caller and + // otherwise returns the larger of the inputs. It + // treats +0 as larger than -0 as per the specification. - if (double.IsNaN(val1)) - { - return val2; - } - - if (double.IsNaN(val2)) + if ((val1 > val2) || double.IsNaN(val1)) { return val1; } - // We do this comparison first and separately to handle the -0.0 to +0.0 comparision - // * Doing (val1 < val2) first could get transformed into (val2 >= val1) by the JIT - // which would then return an incorrect value - if (val1 == val2) { return double.IsNegative(val1) ? val2 : val1; } - return (val1 < val2) ? val2 : val1; + return val2; } [NonVersionable] @@ -593,31 +586,23 @@ public static sbyte Max(sbyte val1, sbyte val2) public static float Max(float val1, float val2) { - // When val1 and val2 are both finite or infinite, return the larger - // * We count +0.0 as larger than -0.0 to match MSVC - // When val1 or val2, but not both, are NaN return the opposite - // * We return the opposite if either is NaN to match MSVC + // This matches the IEEE 754:2019 `maximum` function + // + // It propagates NaN inputs back to the caller and + // otherwise returns the larger of the inputs. It + // treats +0 as larger than -0 as per the specification. - if (float.IsNaN(val1)) - { - return val2; - } - - if (float.IsNaN(val2)) + if ((val1 > val2) || float.IsNaN(val1)) { return val1; } - // We do this comparison first and separately to handle the -0.0 to +0.0 comparision - // * Doing (val1 < val2) first could get transformed into (val2 >= val1) by the JIT - // which would then return an incorrect value - if (val1 == val2) { return float.IsNegative(val1) ? val2 : val1; } - return (val1 < val2) ? val2 : val1; + return val2; } [CLSCompliant(false)] @@ -643,34 +628,26 @@ public static ulong Max(ulong val1, ulong val2) public static double MaxMagnitude(double x, double y) { - // When x and y are both finite or infinite, return the larger magnitude - // * We count +0.0 as larger than -0.0 to match MSVC - // When x or y, but not both, are NaN return the opposite - // * We return the opposite if either is NaN to match MSVC + // This matches the IEEE 754:2019 `maximumMagnitude` function + // + // It propagates NaN inputs back to the caller and + // otherwise returns the input with a larger magnitude. + // It treats +0 as larger than -0 as per the specification. - if (double.IsNaN(x)) - { - return y; - } + double ax = Abs(x); + double ay = Abs(y); - if (double.IsNaN(y)) + if ((ax > ay) || double.IsNaN(ax)) { return x; } - // We do this comparison first and separately to handle the -0.0 to +0.0 comparision - // * Doing (ax < ay) first could get transformed into (ay >= ax) by the JIT which would - // then return an incorrect value - - double ax = Abs(x); - double ay = Abs(y); - if (ax == ay) { return double.IsNegative(x) ? y : x; } - return (ax < ay) ? y : x; + return y; } [NonVersionable] @@ -687,31 +664,23 @@ public static decimal Min(decimal val1, decimal val2) public static double Min(double val1, double val2) { - // When val1 and val2 are both finite or infinite, return the smaller - // * We count -0.0 as smaller than -0.0 to match MSVC - // When val1 or val2, but not both, are NaN return the opposite - // * We return the opposite if either is NaN to match MSVC + // This matches the IEEE 754:2019 `minimum` function + // + // It propagates NaN inputs back to the caller and + // otherwise returns the larger of the inputs. It + // treats +0 as larger than -0 as per the specification. - if (double.IsNaN(val1)) - { - return val2; - } - - if (double.IsNaN(val2)) + if ((val1 < val2) || double.IsNaN(val1)) { return val1; } - // We do this comparison first and separately to handle the -0.0 to +0.0 comparision - // * Doing (val1 < val2) first could get transformed into (val2 >= val1) by the JIT - // which would then return an incorrect value - if (val1 == val2) { return double.IsNegative(val1) ? val1 : val2; } - return (val1 < val2) ? val1 : val2; + return val2; } [NonVersionable] @@ -741,31 +710,23 @@ public static sbyte Min(sbyte val1, sbyte val2) public static float Min(float val1, float val2) { - // When val1 and val2 are both finite or infinite, return the smaller - // * We count -0.0 as smaller than -0.0 to match MSVC - // When val1 or val2, but not both, are NaN return the opposite - // * We return the opposite if either is NaN to match MSVC + // This matches the IEEE 754:2019 `minimum` function + // + // It propagates NaN inputs back to the caller and + // otherwise returns the larger of the inputs. It + // treats +0 as larger than -0 as per the specification. - if (float.IsNaN(val1)) - { - return val2; - } - - if (float.IsNaN(val2)) + if ((val1 < val2) || float.IsNaN(val1)) { return val1; } - // We do this comparison first and separately to handle the -0.0 to +0.0 comparision - // * Doing (val1 < val2) first could get transformed into (val2 >= val1) by the JIT - // which would then return an incorrect value - if (val1 == val2) { return float.IsNegative(val1) ? val1 : val2; } - return (val1 < val2) ? val1 : val2; + return val2; } [CLSCompliant(false)] @@ -791,34 +752,26 @@ public static ulong Min(ulong val1, ulong val2) public static double MinMagnitude(double x, double y) { - // When x and y are both finite or infinite, return the smaller magnitude - // * We count -0.0 as smaller than -0.0 to match MSVC - // When x or y, but not both, are NaN return the opposite - // * We return the opposite if either is NaN to match MSVC + // This matches the IEEE 754:2019 `minimumMagnitude` function + // + // It propagates NaN inputs back to the caller and + // otherwise returns the input with a larger magnitude. + // It treats +0 as larger than -0 as per the specification. - if (double.IsNaN(x)) - { - return y; - } + double ax = Abs(x); + double ay = Abs(y); - if (double.IsNaN(y)) + if ((ax < ay) || double.IsNaN(ax)) { return x; } - // We do this comparison first and separately to handle the -0.0 to +0.0 comparision - // * Doing (ax < ay) first could get transformed into (ay >= ax) by the JIT which would - // then return an incorrect value - - double ax = Abs(x); - double ay = Abs(y); - if (ax == ay) { return double.IsNegative(x) ? x : y; } - return (ax < ay) ? x : y; + return y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -1033,6 +986,7 @@ public static unsafe double Truncate(double d) return d; } + [DoesNotReturn] private static void ThrowMinMaxException(T min, T max) { throw new ArgumentException(SR.Format(SR.Argument_MinMaxValue, min, max)); diff --git a/src/Common/src/CoreLib/System/MathF.cs b/src/Common/src/CoreLib/System/MathF.cs index 0994ed09ae6a..da710a1deae0 100644 --- a/src/Common/src/CoreLib/System/MathF.cs +++ b/src/Common/src/CoreLib/System/MathF.cs @@ -10,7 +10,6 @@ //This class contains only static members and doesn't require serialization. -#nullable enable using System.Runtime.CompilerServices; namespace System @@ -190,34 +189,26 @@ public static float Max(float x, float y) public static float MaxMagnitude(float x, float y) { - // When x and y are both finite or infinite, return the larger magnitude - // * We count +0.0 as larger than -0.0 to match MSVC - // When x or y, but not both, are NaN return the opposite - // * We return the opposite if either is NaN to match MSVC + // This matches the IEEE 754:2019 `maximumMagnitude` function + // + // It propagates NaN inputs back to the caller and + // otherwise returns the input with a larger magnitude. + // It treats +0 as larger than -0 as per the specification. - if (float.IsNaN(x)) - { - return y; - } + float ax = Abs(x); + float ay = Abs(y); - if (float.IsNaN(y)) + if ((ax > ay) || float.IsNaN(ax)) { return x; } - // We do this comparison first and separately to handle the -0.0 to +0.0 comparision - // * Doing (ax < ay) first could get transformed into (ay >= ax) by the JIT which would - // then return an incorrect value - - float ax = Abs(x); - float ay = Abs(y); - if (ax == ay) { return float.IsNegative(x) ? y : x; } - return (ax < ay) ? y : x; + return y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -228,34 +219,26 @@ public static float Min(float x, float y) public static float MinMagnitude(float x, float y) { - // When x and y are both finite or infinite, return the smaller magnitude - // * We count -0.0 as smaller than -0.0 to match MSVC - // When x or y, but not both, are NaN return the opposite - // * We return the opposite if either is NaN to match MSVC + // This matches the IEEE 754:2019 `minimumMagnitude` function + // + // It propagates NaN inputs back to the caller and + // otherwise returns the input with a larger magnitude. + // It treats +0 as larger than -0 as per the specification. - if (float.IsNaN(x)) - { - return y; - } + float ax = Abs(x); + float ay = Abs(y); - if (float.IsNaN(y)) + if ((ax < ay) || float.IsNaN(ax)) { return x; } - // We do this comparison first and separately to handle the -0.0 to +0.0 comparision - // * Doing (ax < ay) first could get transformed into (ay >= ax) by the JIT which would - // then return an incorrect value - - float ax = Abs(x); - float ay = Abs(y); - if (ax == ay) { return float.IsNegative(x) ? x : y; } - return (ax < ay) ? x : y; + return y; } [Intrinsic] diff --git a/src/Common/src/CoreLib/System/MemberAccessException.cs b/src/Common/src/CoreLib/System/MemberAccessException.cs index 5d771ba8484b..41d00166dab6 100644 --- a/src/Common/src/CoreLib/System/MemberAccessException.cs +++ b/src/Common/src/CoreLib/System/MemberAccessException.cs @@ -8,7 +8,6 @@ // access, due to it being removed, private or something similar. //////////////////////////////////////////////////////////////////////////////// -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/Memory.cs b/src/Common/src/CoreLib/System/Memory.cs index 399c6f015146..6d63973a45b1 100644 --- a/src/Common/src/CoreLib/System/Memory.cs +++ b/src/Common/src/CoreLib/System/Memory.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -55,7 +54,7 @@ public Memory(T[]? array) this = default; return; // returns default } - if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) ThrowHelper.ThrowArrayTypeMismatchException(); _object = array; @@ -73,7 +72,7 @@ internal Memory(T[]? array, int start) this = default; return; // returns default } - if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); @@ -93,7 +92,7 @@ internal Memory(T[]? array, int start) /// Returns default when is null. /// Thrown when is covariant and array's type is not exactly T[]. /// - /// Thrown when the specified or end index is not in the range (<0 or >=Length). + /// Thrown when the specified or end index is not in the range (<0 or >Length). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[]? array, int start, int length) @@ -105,7 +104,7 @@ public Memory(T[]? array, int start, int length) this = default; return; // returns default } - if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) ThrowHelper.ThrowArrayTypeMismatchException(); #if BIT64 // See comment in Span.Slice for how this works. @@ -244,7 +243,7 @@ public override string ToString() /// /// The index at which to begin this slice. /// - /// Thrown when the specified index is not in range (<0 or >=Length). + /// Thrown when the specified index is not in range (<0 or >Length). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory Slice(int start) @@ -264,7 +263,7 @@ public Memory Slice(int start) /// The index at which to begin this slice. /// The desired length for the slice (exclusive). /// - /// Thrown when the specified or end index is not in range (<0 or >=Length). + /// Thrown when the specified or end index is not in range (<0 or >Length). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory Slice(int start, int length) diff --git a/src/Common/src/CoreLib/System/MemoryDebugView.cs b/src/Common/src/CoreLib/System/MemoryDebugView.cs index 563d010d61e5..6ab6e5065cf3 100644 --- a/src/Common/src/CoreLib/System/MemoryDebugView.cs +++ b/src/Common/src/CoreLib/System/MemoryDebugView.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System diff --git a/src/Common/src/CoreLib/System/MemoryExtensions.Fast.cs b/src/Common/src/CoreLib/System/MemoryExtensions.Fast.cs index 82f3d2321ef9..6de285d61c20 100644 --- a/src/Common/src/CoreLib/System/MemoryExtensions.Fast.cs +++ b/src/Common/src/CoreLib/System/MemoryExtensions.Fast.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; @@ -238,7 +237,7 @@ public static int ToLower(this ReadOnlySpan source, Span destination if (GlobalizationMode.Invariant) TextInfo.ToLowerAsciiInvariant(source, destination); else - culture!.TextInfo.ChangeCaseToLower(source, destination); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + culture!.TextInfo.ChangeCaseToLower(source, destination); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected return source.Length; } @@ -289,7 +288,7 @@ public static int ToUpper(this ReadOnlySpan source, Span destination if (GlobalizationMode.Invariant) TextInfo.ToUpperAsciiInvariant(source, destination); else - culture!.TextInfo.ChangeCaseToUpper(source, destination); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + culture!.TextInfo.ChangeCaseToUpper(source, destination); // TODO-NULLABLE: Remove ! when [DoesNotReturn] respected return source.Length; } @@ -393,7 +392,7 @@ public static Span AsSpan(this T[]? array, int start) ThrowHelper.ThrowArgumentOutOfRangeException(); return default; } - if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); @@ -415,7 +414,7 @@ public static Span AsSpan(this T[]? array, Index startIndex) return default; } - if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) ThrowHelper.ThrowArrayTypeMismatchException(); int actualIndex = startIndex.GetOffset(array.Length); @@ -442,7 +441,7 @@ public static Span AsSpan(this T[]? array, Range range) return default; } - if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) ThrowHelper.ThrowArrayTypeMismatchException(); (int start, int length) = range.GetOffsetAndLength(array.Length); diff --git a/src/Common/src/CoreLib/System/MemoryExtensions.Trim.cs b/src/Common/src/CoreLib/System/MemoryExtensions.Trim.cs index 5c776cd4ea45..96581c7c0183 100644 --- a/src/Common/src/CoreLib/System/MemoryExtensions.Trim.cs +++ b/src/Common/src/CoreLib/System/MemoryExtensions.Trim.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System diff --git a/src/Common/src/CoreLib/System/MemoryExtensions.cs b/src/Common/src/CoreLib/System/MemoryExtensions.cs index 50130974336d..b9824e23a7ee 100644 --- a/src/Common/src/CoreLib/System/MemoryExtensions.cs +++ b/src/Common/src/CoreLib/System/MemoryExtensions.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -997,7 +996,7 @@ public static Span AsSpan(this T[]? array) /// Returns default when is null. /// Thrown when is covariant and array's type is not exactly T[]. /// - /// Thrown when the specified or end index is not in the range (<0 or >=Length). + /// Thrown when the specified or end index is not in the range (<0 or >Length). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this T[]? array, int start, int length) @@ -1023,7 +1022,7 @@ public static Span AsSpan(this ArraySegment segment) /// Returns default when is null. /// Thrown when is covariant and array's type is not exactly T[]. /// - /// Thrown when the specified or end index is not in the range (<0 or >=segment.Count). + /// Thrown when the specified or end index is not in the range (<0 or >segment.Count). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this ArraySegment segment, int start) @@ -1057,7 +1056,7 @@ public static Span AsSpan(this ArraySegment segment, Index startIndex) /// Returns default when is null. /// Thrown when is covariant and array's type is not exactly T[]. /// - /// Thrown when the specified or end index is not in the range (<0 or >=segment.Count). + /// Thrown when the specified or end index is not in the range (<0 or >segment.Count). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this ArraySegment segment, int start, int length) @@ -1096,7 +1095,7 @@ public static Span AsSpan(this ArraySegment segment, Range range) /// Returns default when is null. /// Thrown when is covariant and array's type is not exactly T[]. /// - /// Thrown when the specified or end index is not in the range (<0 or >=array.Length). + /// Thrown when the specified or end index is not in the range (<0 or >array.Length). /// public static Memory AsMemory(this T[]? array, int start) => new Memory(array, start); @@ -1128,7 +1127,7 @@ public static Memory AsMemory(this T[]? array, Index startIndex) /// Returns default when is null. /// Thrown when is covariant and array's type is not exactly T[]. /// - /// Thrown when the specified or end index is not in the range (<0 or >=Length). + /// Thrown when the specified or end index is not in the range (<0 or >Length). /// public static Memory AsMemory(this T[]? array, int start, int length) => new Memory(array, start, length); @@ -1166,7 +1165,7 @@ public static Memory AsMemory(this T[]? array, Range range) /// Returns default when is null. /// Thrown when is covariant and array's type is not exactly T[]. /// - /// Thrown when the specified or end index is not in the range (<0 or >=segment.Count). + /// Thrown when the specified or end index is not in the range (<0 or >segment.Count). /// public static Memory AsMemory(this ArraySegment segment, int start) { @@ -1186,7 +1185,7 @@ public static Memory AsMemory(this ArraySegment segment, int start) /// Returns default when is null. /// Thrown when is covariant and array's type is not exactly T[]. /// - /// Thrown when the specified or end index is not in the range (<0 or >=segment.Count). + /// Thrown when the specified or end index is not in the range (<0 or >segment.Count). /// public static Memory AsMemory(this ArraySegment segment, int start, int length) { diff --git a/src/Common/src/CoreLib/System/MethodAccessException.cs b/src/Common/src/CoreLib/System/MethodAccessException.cs index 23625490f967..5a9445d0cca4 100644 --- a/src/Common/src/CoreLib/System/MethodAccessException.cs +++ b/src/Common/src/CoreLib/System/MethodAccessException.cs @@ -9,7 +9,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/MidpointRounding.cs b/src/Common/src/CoreLib/System/MidpointRounding.cs index 146fed9bd6b0..835dafe7eeee 100644 --- a/src/Common/src/CoreLib/System/MidpointRounding.cs +++ b/src/Common/src/CoreLib/System/MidpointRounding.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { public enum MidpointRounding diff --git a/src/Common/src/CoreLib/System/MissingFieldException.cs b/src/Common/src/CoreLib/System/MissingFieldException.cs index be41b3592cb6..6297177c1e40 100644 --- a/src/Common/src/CoreLib/System/MissingFieldException.cs +++ b/src/Common/src/CoreLib/System/MissingFieldException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/MissingMemberException.cs b/src/Common/src/CoreLib/System/MissingMemberException.cs index cc8be87286c8..8ba7b53e311a 100644 --- a/src/Common/src/CoreLib/System/MissingMemberException.cs +++ b/src/Common/src/CoreLib/System/MissingMemberException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/MissingMethodException.cs b/src/Common/src/CoreLib/System/MissingMethodException.cs index 8a94ac569614..81e54fb2b0c1 100644 --- a/src/Common/src/CoreLib/System/MissingMethodException.cs +++ b/src/Common/src/CoreLib/System/MissingMethodException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/MulticastNotSupportedException.cs b/src/Common/src/CoreLib/System/MulticastNotSupportedException.cs index 912e569b2664..898b2ebd0dcb 100644 --- a/src/Common/src/CoreLib/System/MulticastNotSupportedException.cs +++ b/src/Common/src/CoreLib/System/MulticastNotSupportedException.cs @@ -7,7 +7,6 @@ // This is thrown when you add multiple callbacks to a non-multicast delegate. //////////////////////////////////////////////////////////////////////////////// -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/NonSerializedAttribute.cs b/src/Common/src/CoreLib/System/NonSerializedAttribute.cs index 2caa285a76a4..cabd5a2aa25a 100644 --- a/src/Common/src/CoreLib/System/NonSerializedAttribute.cs +++ b/src/Common/src/CoreLib/System/NonSerializedAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { [AttributeUsage(AttributeTargets.Field, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/NotFiniteNumberException.cs b/src/Common/src/CoreLib/System/NotFiniteNumberException.cs index af464124eb3b..53a5817a7dc7 100644 --- a/src/Common/src/CoreLib/System/NotFiniteNumberException.cs +++ b/src/Common/src/CoreLib/System/NotFiniteNumberException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/NotImplementedException.cs b/src/Common/src/CoreLib/System/NotImplementedException.cs index 42d207459b44..808bc50a0c99 100644 --- a/src/Common/src/CoreLib/System/NotImplementedException.cs +++ b/src/Common/src/CoreLib/System/NotImplementedException.cs @@ -12,7 +12,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/NotSupportedException.cs b/src/Common/src/CoreLib/System/NotSupportedException.cs index 2fabb8ea06eb..61c186844f33 100644 --- a/src/Common/src/CoreLib/System/NotSupportedException.cs +++ b/src/Common/src/CoreLib/System/NotSupportedException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/NullReferenceException.cs b/src/Common/src/CoreLib/System/NullReferenceException.cs index f95a7699dd14..6b1a0350add7 100644 --- a/src/Common/src/CoreLib/System/NullReferenceException.cs +++ b/src/Common/src/CoreLib/System/NullReferenceException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/Nullable.cs b/src/Common/src/CoreLib/System/Nullable.cs index 10df282d10fb..a34769645895 100644 --- a/src/Common/src/CoreLib/System/Nullable.cs +++ b/src/Common/src/CoreLib/System/Nullable.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections.Generic; using System.Runtime.Versioning; diff --git a/src/Common/src/CoreLib/System/Number.BigInteger.cs b/src/Common/src/CoreLib/System/Number.BigInteger.cs index 33ac49e62516..06ae1e7668cd 100644 --- a/src/Common/src/CoreLib/System/Number.BigInteger.cs +++ b/src/Common/src/CoreLib/System/Number.BigInteger.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Numerics; using System.Runtime.InteropServices; diff --git a/src/Common/src/CoreLib/System/Number.DiyFp.cs b/src/Common/src/CoreLib/System/Number.DiyFp.cs index 5daf2f5d6a5e..bb9fc092bc20 100644 --- a/src/Common/src/CoreLib/System/Number.DiyFp.cs +++ b/src/Common/src/CoreLib/System/Number.DiyFp.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Numerics; diff --git a/src/Common/src/CoreLib/System/Number.Dragon4.cs b/src/Common/src/CoreLib/System/Number.Dragon4.cs index 0dc6c90858bd..b7a6bbaf62c1 100644 --- a/src/Common/src/CoreLib/System/Number.Dragon4.cs +++ b/src/Common/src/CoreLib/System/Number.Dragon4.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Numerics; using Internal.Runtime.CompilerServices; @@ -278,7 +277,7 @@ private static unsafe uint Dragon4(ulong mantissa, int exponent, uint mantissaHi } // Output the exponent of the first digit we will print - decimalExponent = digitExponent - 1; + decimalExponent = --digitExponent; // In preparation for calling BigInteger.HeuristicDivie(), we need to scale up our values such that the highest block of the denominator is greater than or equal to 8. // We also need to guarantee that the numerator can never have a length greater than the denominator after each loop iteration. @@ -316,14 +315,13 @@ private static unsafe uint Dragon4(ulong mantissa, int exponent, uint mantissaHi if (cutoffNumber == -1) { Debug.Assert(isSignificantDigits); + Debug.Assert(digitExponent >= cutoffExponent); // For the unique cutoff mode, we will try to print until we have reached a level of precision that uniquely distinguishes this value from its neighbors. // If we run out of space in the output buffer, we terminate early. while (true) { - digitExponent = digitExponent - 1; - // divide out the scale to extract the digit outputDigit = BigInteger.HeuristicDivide(ref scaledValue, ref scale); Debug.Assert(outputDigit < 10); @@ -352,9 +350,11 @@ private static unsafe uint Dragon4(ulong mantissa, int exponent, uint mantissaHi { BigInteger.Multiply(ref scaledMarginLow, 2, ref *pScaledMarginHigh); } + + digitExponent--; } } - else + else if (digitExponent >= cutoffExponent) { Debug.Assert((cutoffNumber > 0) || ((cutoffNumber == 0) && !isSignificantDigits)); @@ -364,8 +364,6 @@ private static unsafe uint Dragon4(ulong mantissa, int exponent, uint mantissaHi while (true) { - digitExponent = digitExponent - 1; - // divide out the scale to extract the digit outputDigit = BigInteger.HeuristicDivide(ref scaledValue, ref scale); Debug.Assert(outputDigit < 10); @@ -381,7 +379,31 @@ private static unsafe uint Dragon4(ulong mantissa, int exponent, uint mantissaHi // multiply larger by the output base scaledValue.Multiply10(); + digitExponent--; + } + } + else + { + // In the scenario where the first significand digit is after the cutoff, we want to treat that + // first significand digit as the rounding digit and increase the decimalExponent by one. This + // ensures we correctly handle the case where the first significand digit is exactly one after + // the cutoff, it is a 4, and the subsequent digit would round that to 5 inducing a double rounding + // bug when NumberToString is does its own rounding checks. + + decimalExponent++; + + // divide out the scale to extract the digit + outputDigit = BigInteger.HeuristicDivide(ref scaledValue, ref scale); + Debug.Assert(outputDigit < 10); + + if ((outputDigit > 5) || ((outputDigit == 5) && !scaledValue.IsZero())) + { + buffer[curDigit] = (byte)('1'); + curDigit += 1; } + + // return the number of digits output + return (uint)(curDigit); } // round off the final digit diff --git a/src/Common/src/CoreLib/System/Number.Formatting.cs b/src/Common/src/CoreLib/System/Number.Formatting.cs index 378832e5bc06..951d190d189d 100644 --- a/src/Common/src/CoreLib/System/Number.Formatting.cs +++ b/src/Common/src/CoreLib/System/Number.Formatting.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers.Text; using System.Diagnostics; using System.Globalization; diff --git a/src/Common/src/CoreLib/System/Number.Grisu3.cs b/src/Common/src/CoreLib/System/Number.Grisu3.cs index 5ff8d466a34c..96ec7af2f87d 100644 --- a/src/Common/src/CoreLib/System/Number.Grisu3.cs +++ b/src/Common/src/CoreLib/System/Number.Grisu3.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System diff --git a/src/Common/src/CoreLib/System/Number.NumberBuffer.cs b/src/Common/src/CoreLib/System/Number.NumberBuffer.cs index ccedf417aa63..268bdc78b6cf 100644 --- a/src/Common/src/CoreLib/System/Number.NumberBuffer.cs +++ b/src/Common/src/CoreLib/System/Number.NumberBuffer.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Text; using Internal.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/Number.NumberToFloatingPointBits.cs b/src/Common/src/CoreLib/System/Number.NumberToFloatingPointBits.cs index cfe8ce52011e..ac4c7727f323 100644 --- a/src/Common/src/CoreLib/System/Number.NumberToFloatingPointBits.cs +++ b/src/Common/src/CoreLib/System/Number.NumberToFloatingPointBits.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; namespace System diff --git a/src/Common/src/CoreLib/System/Number.Parsing.cs b/src/Common/src/CoreLib/System/Number.Parsing.cs index 3f9f5c1283aa..c5369d1cb68c 100644 --- a/src/Common/src/CoreLib/System/Number.Parsing.cs +++ b/src/Common/src/CoreLib/System/Number.Parsing.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -1927,8 +1927,10 @@ internal enum ParsingStatus Overflow } + [DoesNotReturn] internal static void ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type = 0) => throw GetException(status, type); + [DoesNotReturn] internal static void ThrowOverflowException(TypeCode type) => throw GetException(ParsingStatus.Overflow, type); private static Exception GetException(ParsingStatus status, TypeCode type) diff --git a/src/Common/src/CoreLib/System/Numerics/BitOperations.cs b/src/Common/src/CoreLib/System/Numerics/BitOperations.cs index e2a6720ec68c..3813b9a68977 100644 --- a/src/Common/src/CoreLib/System/Numerics/BitOperations.cs +++ b/src/Common/src/CoreLib/System/Numerics/BitOperations.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; diff --git a/src/Common/src/CoreLib/System/Numerics/Hashing/HashHelpers.cs b/src/Common/src/CoreLib/System/Numerics/Hashing/HashHelpers.cs index ed23f1cae746..fd9d708d3674 100644 --- a/src/Common/src/CoreLib/System/Numerics/Hashing/HashHelpers.cs +++ b/src/Common/src/CoreLib/System/Numerics/Hashing/HashHelpers.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Numerics.Hashing { internal static class HashHelpers diff --git a/src/Common/src/CoreLib/System/Numerics/Vector.cs b/src/Common/src/CoreLib/System/Numerics/Vector.cs index 3f7832a3a0cc..b49d8b172070 100644 --- a/src/Common/src/CoreLib/System/Numerics/Vector.cs +++ b/src/Common/src/CoreLib/System/Numerics/Vector.cs @@ -6,6 +6,7 @@ #if netcoreapp using Internal.Runtime.CompilerServices; #endif +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Numerics.Hashing; using System.Runtime.CompilerServices; @@ -59,10 +60,10 @@ public static int Count [Intrinsic] get { - return s_count; + ThrowHelper.ThrowForUnsupportedVectorBaseType(); + return Unsafe.SizeOf>() / Unsafe.SizeOf(); } } - private static readonly int s_count = InitializeCount(); /// /// Returns a vector containing all zeroes. @@ -101,71 +102,6 @@ internal static Vector AllOnes private static readonly Vector s_allOnes = new Vector(GetAllBitsSetValue()); #endregion Static Members - #region Static Initialization - private struct VectorSizeHelper - { - internal Vector _placeholder; - internal byte _byte; - } - - // Calculates the size of this struct in bytes, by computing the offset of a field in a structure - private static unsafe int InitializeCount() - { - VectorSizeHelper vsh; - byte* vectorBase = &vsh._placeholder.register.byte_0; - byte* byteBase = &vsh._byte; - int vectorSizeInBytes = (int)(byteBase - vectorBase); - - int typeSizeInBytes = -1; - if (typeof(T) == typeof(byte)) - { - typeSizeInBytes = sizeof(byte); - } - else if (typeof(T) == typeof(sbyte)) - { - typeSizeInBytes = sizeof(sbyte); - } - else if (typeof(T) == typeof(ushort)) - { - typeSizeInBytes = sizeof(ushort); - } - else if (typeof(T) == typeof(short)) - { - typeSizeInBytes = sizeof(short); - } - else if (typeof(T) == typeof(uint)) - { - typeSizeInBytes = sizeof(uint); - } - else if (typeof(T) == typeof(int)) - { - typeSizeInBytes = sizeof(int); - } - else if (typeof(T) == typeof(ulong)) - { - typeSizeInBytes = sizeof(ulong); - } - else if (typeof(T) == typeof(long)) - { - typeSizeInBytes = sizeof(long); - } - else if (typeof(T) == typeof(float)) - { - typeSizeInBytes = sizeof(float); - } - else if (typeof(T) == typeof(double)) - { - typeSizeInBytes = sizeof(double); - } - else - { - throw new NotSupportedException(SR.Arg_TypeNotSupported); - } - - return vectorSizeInBytes / typeSizeInBytes; - } - #endregion Static Initialization - #region Constructors /// /// Constructs a vector whose components are all value @@ -779,37 +715,81 @@ private Vector(ref Register existingRegister) #if netcoreapp /// - /// Constructs a vector from the given span. The span must contain at least Vector'T.Count elements. + /// Constructs a vector from the given . The span must contain at least elements. /// - public Vector(Span values) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector(ReadOnlySpan values) : this() { - if ((typeof(T) == typeof(byte)) - || (typeof(T) == typeof(sbyte)) - || (typeof(T) == typeof(ushort)) - || (typeof(T) == typeof(short)) - || (typeof(T) == typeof(uint)) - || (typeof(T) == typeof(int)) - || (typeof(T) == typeof(ulong)) - || (typeof(T) == typeof(long)) - || (typeof(T) == typeof(float)) - || (typeof(T) == typeof(double))) + ThrowHelper.ThrowForUnsupportedVectorBaseType(); + if (values.Length < Vector.Count) { - if (values.Length < Count) - { - throw new IndexOutOfRangeException(SR.Format(SR.Arg_InsufficientNumberOfElements, Vector.Count, nameof(values))); - } - this = Unsafe.ReadUnaligned>(ref Unsafe.As(ref MemoryMarshal.GetReference(values))); + Vector.ThrowInsufficientNumberOfElementsException(Vector.Count); } - else + this = Unsafe.ReadUnaligned>(ref MemoryMarshal.GetReference(values)); + } + + /// + /// Constructs a vector from the given . The span must contain at least elements. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector(ReadOnlySpan values) + : this() + { + if (values.Length < Count) { - throw new NotSupportedException(SR.Arg_TypeNotSupported); + Vector.ThrowInsufficientNumberOfElementsException(Vector.Count); } + this = Unsafe.ReadUnaligned>(ref Unsafe.As(ref MemoryMarshal.GetReference(values))); + } + + /// + /// Constructs a vector from the given . The span must contain at least elements. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector(Span values) + : this() + { + if (values.Length < Count) + { + Vector.ThrowInsufficientNumberOfElementsException(Vector.Count); + } + this = Unsafe.ReadUnaligned>(ref Unsafe.As(ref MemoryMarshal.GetReference(values))); } #endif #endregion Constructors #region Public Instance Methods + /// + /// Copies the vector to the given . The destination span must be at least size . + /// + /// The destination span which the values are copied into + /// If number of elements in source vector is greater than those available in destination span + public readonly void CopyTo(Span destination) + { + ThrowHelper.ThrowForUnsupportedVectorBaseType(); + if ((uint)destination.Length < (uint)Vector.Count) + { + ThrowHelper.ThrowArgumentException_DestinationTooShort(); + } + Unsafe.WriteUnaligned>(ref MemoryMarshal.GetReference(destination), this); + } + + /// + /// Copies the vector to the given . The destination span must be at least size . + /// + /// The destination span which the values are copied into + /// If number of elements in source vector is greater than those available in destination span + public readonly void CopyTo(Span destination) + { + if ((uint)destination.Length < (uint)Count) + { + ThrowHelper.ThrowArgumentException_DestinationTooShort(); + } + + Unsafe.WriteUnaligned>(ref Unsafe.As(ref MemoryMarshal.GetReference(destination)), this); + } + /// /// Copies the vector to the given destination array. The destination array must be at least size Vector'T.Count. /// @@ -817,7 +797,7 @@ public Vector(Span values) /// If the destination array is null /// If number of elements in source vector is greater than those available in destination array [Intrinsic] - public unsafe void CopyTo(T[] destination) + public unsafe readonly void CopyTo(T[] destination) { CopyTo(destination, 0); } @@ -831,7 +811,7 @@ public unsafe void CopyTo(T[] destination) /// If index is greater than end of the array or index is less than zero /// If number of elements in source vector is greater than those available in destination array [Intrinsic] - public unsafe void CopyTo(T[] destination, int startIndex) + public unsafe readonly void CopyTo(T[] destination, int startIndex) { if (destination == null) { @@ -1104,7 +1084,7 @@ public unsafe void CopyTo(T[] destination, int startIndex) /// /// Returns the element at the given index. /// - public unsafe T this[int index] + public unsafe readonly T this[int index] { [Intrinsic] get @@ -1196,7 +1176,7 @@ public unsafe T this[int index] /// The Object to compare against. /// True if the Object is equal to this vector; False otherwise. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public override bool Equals(object? obj) + public override readonly bool Equals(object? obj) { if (!(obj is Vector)) { @@ -1211,7 +1191,7 @@ public override bool Equals(object? obj) /// The vector to compare this instance to. /// True if the other vector is equal to this instance; False otherwise. [Intrinsic] - public bool Equals(Vector other) + public readonly bool Equals(Vector other) { if (Vector.IsHardwareAccelerated) { @@ -1343,7 +1323,7 @@ public bool Equals(Vector other) /// Returns the hash code for this instance. /// /// The hash code. - public override int GetHashCode() + public override readonly int GetHashCode() { int hash = 0; @@ -1553,7 +1533,7 @@ public override int GetHashCode() /// Returns a String representing this vector. /// /// The string representation. - public override string ToString() + public override readonly string ToString() { return ToString("G", CultureInfo.CurrentCulture); } @@ -1563,7 +1543,7 @@ public override string ToString() /// /// The format of individual elements. /// The string representation. - public string ToString(string? format) + public readonly string ToString(string? format) { return ToString(format, CultureInfo.CurrentCulture); } @@ -1575,7 +1555,7 @@ public string ToString(string? format) /// The format of individual elements. /// The format provider to use when formatting elements. /// The string representation. - public string ToString(string? format, IFormatProvider? formatProvider) + public readonly string ToString(string? format, IFormatProvider? formatProvider) { StringBuilder sb = new StringBuilder(); string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; @@ -1591,6 +1571,41 @@ public string ToString(string? format, IFormatProvider? formatProvider) sb.Append('>'); return sb.ToString(); } + + /// + /// Attempts to copy the vector to the given . The destination span must be at least size . + /// + /// The destination span which the values are copied into + /// True if the source vector was successfully copied to . False if + /// is not large enough to hold the source vector. + public readonly bool TryCopyTo(Span destination) + { + ThrowHelper.ThrowForUnsupportedVectorBaseType(); + if ((uint)destination.Length < (uint)Vector.Count) + { + return false; + } + + Unsafe.WriteUnaligned>(ref MemoryMarshal.GetReference(destination), this); + return true; + } + + /// + /// Attempts to copy the vector to the given . The destination span must be at least size . + /// + /// The destination span which the values are copied into + /// True if the source vector was successfully copied to . False if + /// is not large enough to hold the source vector. + public readonly bool TryCopyTo(Span destination) + { + if ((uint)destination.Length < (uint)Count) + { + return false; + } + + Unsafe.WriteUnaligned>(ref Unsafe.As(ref MemoryMarshal.GetReference(destination)), this); + return true; + } #endregion Public Instance Methods #region Arithmetic Operators @@ -5335,5 +5350,13 @@ public static unsafe Vector ConvertToUInt64(Vector value) } #endregion Same-Size Conversion + + #region Throw Helpers + [DoesNotReturn] + internal static void ThrowInsufficientNumberOfElementsException(int requiredElementCount) + { + throw new IndexOutOfRangeException(SR.Format(SR.Arg_InsufficientNumberOfElements, requiredElementCount, "values")); + } + #endregion } } diff --git a/src/Common/src/CoreLib/System/Numerics/Vector.tt b/src/Common/src/CoreLib/System/Numerics/Vector.tt index 5132b09a4a52..ed2b606e556e 100644 --- a/src/Common/src/CoreLib/System/Numerics/Vector.tt +++ b/src/Common/src/CoreLib/System/Numerics/Vector.tt @@ -64,10 +64,10 @@ namespace System.Numerics [Intrinsic] get { - return s_count; + ThrowHelper.ThrowForUnsupportedVectorBaseType(); + return Unsafe.SizeOf>() / Unsafe.SizeOf(); } } - private static readonly int s_count = InitializeCount(); /// /// Returns a vector containing all zeroes. @@ -106,42 +106,6 @@ namespace System.Numerics private static readonly Vector s_allOnes = new Vector(GetAllBitsSetValue()); #endregion Static Members - #region Static Initialization - private struct VectorSizeHelper - { - internal Vector _placeholder; - internal byte _byte; - } - - // Calculates the size of this struct in bytes, by computing the offset of a field in a structure - private static unsafe int InitializeCount() - { - VectorSizeHelper vsh; - byte* vectorBase = &vsh._placeholder.register.byte_0; - byte* byteBase = &vsh._byte; - int vectorSizeInBytes = (int)(byteBase - vectorBase); - - int typeSizeInBytes = -1; -<# - foreach (Type type in supportedTypes) - { -#> - <#=GenerateIfStatementHeader(type)#> - { - typeSizeInBytes = sizeof(<#=typeAliases[type]#>); - } -<# - } -#> - else - { - throw new NotSupportedException(SR.Arg_TypeNotSupported); - } - - return vectorSizeInBytes / typeSizeInBytes; - } - #endregion Static Initialization - #region Constructors /// /// Constructs a vector whose components are all value @@ -305,28 +269,81 @@ namespace System.Numerics #if netcoreapp /// - /// Constructs a vector from the given span. The span must contain at least Vector'T.Count elements. + /// Constructs a vector from the given . The span must contain at least elements. /// - public Vector(Span values) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector(ReadOnlySpan values) : this() { - <#=GenerateIfConditionAllTypes(supportedTypes)#> + ThrowHelper.ThrowForUnsupportedVectorBaseType(); + if (values.Length < Vector.Count) { - if (values.Length < Count) - { - throw new IndexOutOfRangeException(SR.Format(SR.Arg_InsufficientNumberOfElements, Vector.Count, nameof(values))); - } - this = Unsafe.ReadUnaligned>(ref Unsafe.As(ref MemoryMarshal.GetReference(values))); + Vector.ThrowInsufficientNumberOfElementsException(Vector.Count); } - else + this = Unsafe.ReadUnaligned>(ref MemoryMarshal.GetReference(values)); + } + + /// + /// Constructs a vector from the given . The span must contain at least elements. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector(ReadOnlySpan values) + : this() + { + if (values.Length < Count) { - throw new NotSupportedException(SR.Arg_TypeNotSupported); + Vector.ThrowInsufficientNumberOfElementsException(Vector.Count); + } + this = Unsafe.ReadUnaligned>(ref Unsafe.As(ref MemoryMarshal.GetReference(values))); + } + + /// + /// Constructs a vector from the given . The span must contain at least elements. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector(Span values) + : this() + { + if (values.Length < Count) + { + Vector.ThrowInsufficientNumberOfElementsException(Vector.Count); } + this = Unsafe.ReadUnaligned>(ref Unsafe.As(ref MemoryMarshal.GetReference(values))); } #endif #endregion Constructors #region Public Instance Methods + /// + /// Copies the vector to the given . The destination span must be at least size . + /// + /// The destination span which the values are copied into + /// If number of elements in source vector is greater than those available in destination span + public readonly void CopyTo(Span destination) + { + ThrowHelper.ThrowForUnsupportedVectorBaseType(); + if ((uint)destination.Length < (uint)Vector.Count) + { + ThrowHelper.ThrowArgumentException_DestinationTooShort(); + } + Unsafe.WriteUnaligned>(ref MemoryMarshal.GetReference(destination), this); + } + + /// + /// Copies the vector to the given . The destination span must be at least size . + /// + /// The destination span which the values are copied into + /// If number of elements in source vector is greater than those available in destination span + public readonly void CopyTo(Span destination) + { + if ((uint)destination.Length < (uint)Count) + { + ThrowHelper.ThrowArgumentException_DestinationTooShort(); + } + + Unsafe.WriteUnaligned>(ref Unsafe.As(ref MemoryMarshal.GetReference(destination)), this); + } + /// /// Copies the vector to the given destination array. The destination array must be at least size Vector'T.Count. /// @@ -334,7 +351,7 @@ namespace System.Numerics /// If the destination array is null /// If number of elements in source vector is greater than those available in destination array [Intrinsic] - public unsafe void CopyTo(T[] destination) + public unsafe readonly void CopyTo(T[] destination) { CopyTo(destination, 0); } @@ -348,7 +365,7 @@ namespace System.Numerics /// If index is greater than end of the array or index is less than zero /// If number of elements in source vector is greater than those available in destination array [Intrinsic] - public unsafe void CopyTo(T[] destination, int startIndex) + public unsafe readonly void CopyTo(T[] destination, int startIndex) { if (destination == null) { @@ -415,7 +432,7 @@ namespace System.Numerics /// /// Returns the element at the given index. /// - public unsafe T this[int index] + public unsafe readonly T this[int index] { [Intrinsic] get @@ -451,7 +468,7 @@ namespace System.Numerics /// The Object to compare against. /// True if the Object is equal to this vector; False otherwise. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public override bool Equals(object? obj) + public override readonly bool Equals(object? obj) { if (!(obj is Vector)) { @@ -466,7 +483,7 @@ namespace System.Numerics /// The vector to compare this instance to. /// True if the other vector is equal to this instance; False otherwise. [Intrinsic] - public bool Equals(Vector other) + public readonly bool Equals(Vector other) { if (Vector.IsHardwareAccelerated) { @@ -524,7 +541,7 @@ namespace System.Numerics /// Returns the hash code for this instance. /// /// The hash code. - public override int GetHashCode() + public override readonly int GetHashCode() { int hash = 0; @@ -582,7 +599,7 @@ namespace System.Numerics /// Returns a String representing this vector. /// /// The string representation. - public override string ToString() + public override readonly string ToString() { return ToString("G", CultureInfo.CurrentCulture); } @@ -592,7 +609,7 @@ namespace System.Numerics /// /// The format of individual elements. /// The string representation. - public string ToString(string? format) + public readonly string ToString(string? format) { return ToString(format, CultureInfo.CurrentCulture); } @@ -604,7 +621,7 @@ namespace System.Numerics /// The format of individual elements. /// The format provider to use when formatting elements. /// The string representation. - public string ToString(string? format, IFormatProvider? formatProvider) + public readonly string ToString(string? format, IFormatProvider? formatProvider) { StringBuilder sb = new StringBuilder(); string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; @@ -620,6 +637,41 @@ namespace System.Numerics sb.Append('>'); return sb.ToString(); } + + /// + /// Attempts to copy the vector to the given . The destination span must be at least size . + /// + /// The destination span which the values are copied into + /// True if the source vector was successfully copied to . False if + /// is not large enough to hold the source vector. + public readonly bool TryCopyTo(Span destination) + { + ThrowHelper.ThrowForUnsupportedVectorBaseType(); + if ((uint)destination.Length < (uint)Vector.Count) + { + return false; + } + + Unsafe.WriteUnaligned>(ref MemoryMarshal.GetReference(destination), this); + return true; + } + + /// + /// Attempts to copy the vector to the given . The destination span must be at least size . + /// + /// The destination span which the values are copied into + /// True if the source vector was successfully copied to . False if + /// is not large enough to hold the source vector. + public readonly bool TryCopyTo(Span destination) + { + if ((uint)destination.Length < (uint)Count) + { + return false; + } + + Unsafe.WriteUnaligned>(ref Unsafe.As(ref MemoryMarshal.GetReference(destination)), this); + return true; + } #endregion Public Instance Methods #region Arithmetic Operators @@ -1836,5 +1888,13 @@ namespace System.Numerics } #> #endregion Same-Size Conversion + + #region Throw Helpers + [DoesNotReturn] + internal static void ThrowInsufficientNumberOfElementsException(int requiredElementCount) + { + throw new IndexOutOfRangeException(SR.Format(SR.Arg_InsufficientNumberOfElements, requiredElementCount, "values")); + } + #endregion } } diff --git a/src/Common/src/CoreLib/System/Numerics/Vector_Operations.cs b/src/Common/src/CoreLib/System/Numerics/Vector_Operations.cs index 5e7bc607c733..567a0a78eb2e 100644 --- a/src/Common/src/CoreLib/System/Numerics/Vector_Operations.cs +++ b/src/Common/src/CoreLib/System/Numerics/Vector_Operations.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; namespace System.Numerics diff --git a/src/Common/src/CoreLib/System/Object.cs b/src/Common/src/CoreLib/System/Object.cs index 2bdb5c545ab7..91370bbf64d8 100644 --- a/src/Common/src/CoreLib/System/Object.cs +++ b/src/Common/src/CoreLib/System/Object.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; diff --git a/src/Common/src/CoreLib/System/ObjectDisposedException.cs b/src/Common/src/CoreLib/System/ObjectDisposedException.cs index 450a9597e34a..f2bd7e7028f4 100644 --- a/src/Common/src/CoreLib/System/ObjectDisposedException.cs +++ b/src/Common/src/CoreLib/System/ObjectDisposedException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Serialization; diff --git a/src/Common/src/CoreLib/System/ObsoleteAttribute.cs b/src/Common/src/CoreLib/System/ObsoleteAttribute.cs index dbad93f99347..16ad7ca9c0f0 100644 --- a/src/Common/src/CoreLib/System/ObsoleteAttribute.cs +++ b/src/Common/src/CoreLib/System/ObsoleteAttribute.cs @@ -11,7 +11,6 @@ ** ===========================================================*/ -#nullable enable namespace System { // This attribute is attached to members that are not to be used any longer. diff --git a/src/Common/src/CoreLib/System/OperatingSystem.cs b/src/Common/src/CoreLib/System/OperatingSystem.cs index 2e806de778dc..046ce263b40b 100644 --- a/src/Common/src/CoreLib/System/OperatingSystem.cs +++ b/src/Common/src/CoreLib/System/OperatingSystem.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.Serialization; diff --git a/src/Common/src/CoreLib/System/OperationCanceledException.cs b/src/Common/src/CoreLib/System/OperationCanceledException.cs index 029024603e3b..09e708b679ec 100644 --- a/src/Common/src/CoreLib/System/OperationCanceledException.cs +++ b/src/Common/src/CoreLib/System/OperationCanceledException.cs @@ -11,7 +11,6 @@ ** ===========================================================*/ -#nullable enable using System; using System.Runtime.Serialization; using System.Threading; diff --git a/src/Common/src/CoreLib/System/OutOfMemoryException.cs b/src/Common/src/CoreLib/System/OutOfMemoryException.cs index 336618c2a08e..0a079959343d 100644 --- a/src/Common/src/CoreLib/System/OutOfMemoryException.cs +++ b/src/Common/src/CoreLib/System/OutOfMemoryException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/OverflowException.cs b/src/Common/src/CoreLib/System/OverflowException.cs index 172ecf0f6c01..34e63b8e7170 100644 --- a/src/Common/src/CoreLib/System/OverflowException.cs +++ b/src/Common/src/CoreLib/System/OverflowException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/ParamArrayAttribute.cs b/src/Common/src/CoreLib/System/ParamArrayAttribute.cs index 8faffc4eeaab..d3c3d46d569a 100644 --- a/src/Common/src/CoreLib/System/ParamArrayAttribute.cs +++ b/src/Common/src/CoreLib/System/ParamArrayAttribute.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable namespace System { [AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)] diff --git a/src/Common/src/CoreLib/System/ParamsArray.cs b/src/Common/src/CoreLib/System/ParamsArray.cs index 91b2bd1d8675..9114c281d639 100644 --- a/src/Common/src/CoreLib/System/ParamsArray.cs +++ b/src/Common/src/CoreLib/System/ParamsArray.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { internal readonly struct ParamsArray diff --git a/src/Common/src/CoreLib/System/ParseNumbers.cs b/src/Common/src/CoreLib/System/ParseNumbers.cs index ab04cf6b8af2..0978186902d4 100644 --- a/src/Common/src/CoreLib/System/ParseNumbers.cs +++ b/src/Common/src/CoreLib/System/ParseNumbers.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/PasteArguments.Unix.cs b/src/Common/src/CoreLib/System/PasteArguments.Unix.cs index fdad698b95e9..1a4d92850f89 100644 --- a/src/Common/src/CoreLib/System/PasteArguments.Unix.cs +++ b/src/Common/src/CoreLib/System/PasteArguments.Unix.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; diff --git a/src/Common/src/CoreLib/System/PasteArguments.Windows.cs b/src/Common/src/CoreLib/System/PasteArguments.Windows.cs index 42a817b428e6..7cdcbc4533a0 100644 --- a/src/Common/src/CoreLib/System/PasteArguments.Windows.cs +++ b/src/Common/src/CoreLib/System/PasteArguments.Windows.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; diff --git a/src/Common/src/CoreLib/System/PasteArguments.cs b/src/Common/src/CoreLib/System/PasteArguments.cs index afa2e4419e0c..c088fd4eb737 100644 --- a/src/Common/src/CoreLib/System/PasteArguments.cs +++ b/src/Common/src/CoreLib/System/PasteArguments.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Text; namespace System diff --git a/src/Common/src/CoreLib/System/PlatformID.cs b/src/Common/src/CoreLib/System/PlatformID.cs index 0ec46f3d4372..2eda3c05f30e 100644 --- a/src/Common/src/CoreLib/System/PlatformID.cs +++ b/src/Common/src/CoreLib/System/PlatformID.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.ComponentModel; namespace System diff --git a/src/Common/src/CoreLib/System/PlatformNotSupportedException.cs b/src/Common/src/CoreLib/System/PlatformNotSupportedException.cs index ee953ce16bef..7e3f9ae01112 100644 --- a/src/Common/src/CoreLib/System/PlatformNotSupportedException.cs +++ b/src/Common/src/CoreLib/System/PlatformNotSupportedException.cs @@ -11,7 +11,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/Progress.cs b/src/Common/src/CoreLib/System/Progress.cs index 4dae2b190831..f29849378b11 100644 --- a/src/Common/src/CoreLib/System/Progress.cs +++ b/src/Common/src/CoreLib/System/Progress.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Threading; using System.Diagnostics; @@ -82,9 +81,9 @@ protected virtual void OnReport(T value) /// Invokes the action and event callbacks. /// The progress value. - private void InvokeHandlers(object state) + private void InvokeHandlers(object? state) { - T value = (T)state; + T value = (T)state!; Action? handler = _handler; EventHandler changedEvent = ProgressChanged; diff --git a/src/Common/src/CoreLib/System/Random.cs b/src/Common/src/CoreLib/System/Random.cs index 92daa51aac8e..ed79732c25a1 100644 --- a/src/Common/src/CoreLib/System/Random.cs +++ b/src/Common/src/CoreLib/System/Random.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System { public class Random diff --git a/src/Common/src/CoreLib/System/Range.cs b/src/Common/src/CoreLib/System/Range.cs index bad059cbe6ab..0a729b2a9ce0 100644 --- a/src/Common/src/CoreLib/System/Range.cs +++ b/src/Common/src/CoreLib/System/Range.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; @@ -96,15 +95,15 @@ public override string ToString() /// Create a Range object starting from first element to the end. public static Range All => new Range(Index.Start, Index.End); - /// Destruct the range object according to a collection length and return the start offset from the beginning and the length of this range. - /// The length of the collection that the range will be used with. length has to be a positive value + /// Calculate the start offset and length of range object using a collection length. + /// The length of the collection that the range will be used with. length has to be a positive value. /// /// For performance reason, we don't validate the input length parameter against negative values. /// It is expected Range will be used with collections which always have non negative length/count. /// We validate the range is inside the length scope though. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public OffsetAndLength GetOffsetAndLength(int length) + public (int Offset, int Length) GetOffsetAndLength(int length) { int start; Index startIndex = Start; @@ -125,25 +124,7 @@ public OffsetAndLength GetOffsetAndLength(int length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); } - return new OffsetAndLength(start, end - start); - } - - public readonly struct OffsetAndLength - { - public int Offset { get; } - public int Length { get; } - - public OffsetAndLength(int offset, int length) - { - Offset = offset; - Length = length; - } - - public void Deconstruct(out int offset, out int length) - { - offset = Offset; - length = Length; - } + return (start, end - start); } } } diff --git a/src/Common/src/CoreLib/System/RankException.cs b/src/Common/src/CoreLib/System/RankException.cs index 135a6c9d469a..0f6176252f72 100644 --- a/src/Common/src/CoreLib/System/RankException.cs +++ b/src/Common/src/CoreLib/System/RankException.cs @@ -12,7 +12,6 @@ ** =============================================================================*/ -#nullable enable using System.Runtime.Serialization; namespace System diff --git a/src/Common/src/CoreLib/System/ReadOnlyMemory.cs b/src/Common/src/CoreLib/System/ReadOnlyMemory.cs index 37008d7c158a..4a22075bd0d1 100644 --- a/src/Common/src/CoreLib/System/ReadOnlyMemory.cs +++ b/src/Common/src/CoreLib/System/ReadOnlyMemory.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -73,7 +72,7 @@ public ReadOnlyMemory(T[]? array) /// Returns default when is null. /// Thrown when is covariant and array's type is not exactly T[]. /// - /// Thrown when the specified or end index is not in the range (<0 or >=Length). + /// Thrown when the specified or end index is not in the range (<0 or >Length). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[]? array, int start, int length) @@ -173,7 +172,7 @@ public override string ToString() /// /// The index at which to begin this slice. /// - /// Thrown when the specified index is not in range (<0 or >=Length). + /// Thrown when the specified index is not in range (<0 or >Length). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory Slice(int start) @@ -193,7 +192,7 @@ public ReadOnlyMemory Slice(int start) /// The index at which to begin this slice. /// The desired length for the slice (exclusive). /// - /// Thrown when the specified or end index is not in range (<0 or >=Length). + /// Thrown when the specified or end index is not in range (<0 or >Length). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory Slice(int start, int length) diff --git a/src/Common/src/CoreLib/System/ReadOnlySpan.Fast.cs b/src/Common/src/CoreLib/System/ReadOnlySpan.Fast.cs index 1968a41d160e..8a5b7e7d972d 100644 --- a/src/Common/src/CoreLib/System/ReadOnlySpan.Fast.cs +++ b/src/Common/src/CoreLib/System/ReadOnlySpan.Fast.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Versioning; @@ -63,7 +62,7 @@ public ReadOnlySpan(T[]? array) /// The number of items in the read-only span. /// Returns default when is null. /// - /// Thrown when the specified or end index is not in the range (<0 or >=Length). + /// Thrown when the specified or end index is not in the range (<0 or >Length). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[]? array, int start, int length) @@ -247,7 +246,7 @@ public override string ToString() /// /// The index at which to begin this slice. /// - /// Thrown when the specified index is not in range (<0 or >=Length). + /// Thrown when the specified index is not in range (<0 or >Length). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan Slice(int start) @@ -264,7 +263,7 @@ public ReadOnlySpan Slice(int start) /// The index at which to begin this slice. /// The desired length for the slice (exclusive). /// - /// Thrown when the specified or end index is not in range (<0 or >=Length). + /// Thrown when the specified or end index is not in range (<0 or >Length). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan Slice(int start, int length) diff --git a/src/Common/src/CoreLib/System/ReadOnlySpan.cs b/src/Common/src/CoreLib/System/ReadOnlySpan.cs index 2533d1d8b878..e91ff7ea5f34 100644 --- a/src/Common/src/CoreLib/System/ReadOnlySpan.cs +++ b/src/Common/src/CoreLib/System/ReadOnlySpan.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/CoreLib/System/Reflection/AmbiguousMatchException.cs b/src/Common/src/CoreLib/System/Reflection/AmbiguousMatchException.cs index aa321e99f185..7db74c65564b 100644 --- a/src/Common/src/CoreLib/System/Reflection/AmbiguousMatchException.cs +++ b/src/Common/src/CoreLib/System/Reflection/AmbiguousMatchException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System.Reflection diff --git a/src/Common/src/CoreLib/System/Reflection/Assembly.cs b/src/Common/src/CoreLib/System/Reflection/Assembly.cs index 1e9699f62f27..78ab61b4a350 100644 --- a/src/Common/src/CoreLib/System/Reflection/Assembly.cs +++ b/src/Common/src/CoreLib/System/Reflection/Assembly.cs @@ -73,19 +73,19 @@ public virtual Type[] GetTypes() public virtual Type[] GetExportedTypes() { throw NotImplemented.ByDesign; } public virtual Type[] GetForwardedTypes() { throw NotImplemented.ByDesign; } - public virtual string CodeBase { get { throw NotImplemented.ByDesign; } } - public virtual MethodInfo EntryPoint { get { throw NotImplemented.ByDesign; } } - public virtual string FullName { get { throw NotImplemented.ByDesign; } } + public virtual string? CodeBase { get { throw NotImplemented.ByDesign; } } + public virtual MethodInfo? EntryPoint { get { throw NotImplemented.ByDesign; } } + public virtual string? FullName { get { throw NotImplemented.ByDesign; } } public virtual string ImageRuntimeVersion { get { throw NotImplemented.ByDesign; } } public virtual bool IsDynamic => false; public virtual string Location { get { throw NotImplemented.ByDesign; } } public virtual bool ReflectionOnly { get { throw NotImplemented.ByDesign; } } public virtual bool IsCollectible => true; - public virtual ManifestResourceInfo GetManifestResourceInfo(string resourceName) { throw NotImplemented.ByDesign; } + public virtual ManifestResourceInfo? GetManifestResourceInfo(string resourceName) { throw NotImplemented.ByDesign; } public virtual string[] GetManifestResourceNames() { throw NotImplemented.ByDesign; } - public virtual Stream GetManifestResourceStream(string name) { throw NotImplemented.ByDesign; } - public virtual Stream GetManifestResourceStream(Type type, string name) { throw NotImplemented.ByDesign; } + public virtual Stream? GetManifestResourceStream(string name) { throw NotImplemented.ByDesign; } + public virtual Stream? GetManifestResourceStream(Type type, string name) { throw NotImplemented.ByDesign; } public bool IsFullyTrusted => true; @@ -106,9 +106,9 @@ public virtual Type[] GetTypes() public virtual string EscapedCodeBase => AssemblyName.EscapeCodeBase(CodeBase); - public object CreateInstance(string typeName) => CreateInstance(typeName, false, BindingFlags.Public | BindingFlags.Instance, binder: null, args: null, culture: null, activationAttributes: null); - public object CreateInstance(string typeName, bool ignoreCase) => CreateInstance(typeName, ignoreCase, BindingFlags.Public | BindingFlags.Instance, binder: null, args: null, culture: null, activationAttributes: null); - public virtual object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) + public object? CreateInstance(string typeName) => CreateInstance(typeName, false, BindingFlags.Public | BindingFlags.Instance, binder: null, args: null, culture: null, activationAttributes: null); + public object? CreateInstance(string typeName, bool ignoreCase) => CreateInstance(typeName, ignoreCase, BindingFlags.Public | BindingFlags.Instance, binder: null, args: null, culture: null, activationAttributes: null); + public virtual object? CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object[]? args, CultureInfo? culture, object[]? activationAttributes) { Type t = GetType(typeName, throwOnError: false, ignoreCase: ignoreCase); if (t == null) @@ -119,7 +119,7 @@ public virtual object CreateInstance(string typeName, bool ignoreCase, BindingFl public virtual event ModuleResolveEventHandler ModuleResolve { add { throw NotImplemented.ByDesign; } remove { throw NotImplemented.ByDesign; } } - public virtual Module ManifestModule { get { throw NotImplemented.ByDesign; } } + public virtual Module? ManifestModule { get { throw NotImplemented.ByDesign; } } public virtual Module GetModule(string name) { throw NotImplemented.ByDesign; } public Module[] GetModules() => GetModules(getResourceModules: false); @@ -132,9 +132,9 @@ public virtual object CreateInstance(string typeName, bool ignoreCase, BindingFl public virtual AssemblyName[] GetReferencedAssemblies() { throw NotImplemented.ByDesign; } public virtual Assembly GetSatelliteAssembly(CultureInfo culture) { throw NotImplemented.ByDesign; } - public virtual Assembly GetSatelliteAssembly(CultureInfo culture, Version version) { throw NotImplemented.ByDesign; } + public virtual Assembly GetSatelliteAssembly(CultureInfo culture, Version? version) { throw NotImplemented.ByDesign; } - public virtual FileStream GetFile(string name) { throw NotImplemented.ByDesign; } + public virtual FileStream? GetFile(string name) { throw NotImplemented.ByDesign; } public virtual FileStream[] GetFiles() => GetFiles(getResourceModules: false); public virtual FileStream[] GetFiles(bool getResourceModules) { throw NotImplemented.ByDesign; } @@ -142,11 +142,7 @@ public virtual object CreateInstance(string typeName, bool ignoreCase, BindingFl public override string ToString() { - string displayName = FullName; - if (displayName == null) - return base.ToString(); - else - return displayName; + return FullName ?? base.ToString()!; } /* @@ -155,11 +151,11 @@ public override string ToString() public virtual bool GlobalAssemblyCache { get { throw NotImplemented.ByDesign; } } public virtual long HostContext { get { throw NotImplemented.ByDesign; } } - public override bool Equals(object o) => base.Equals(o); + public override bool Equals(object? o) => base.Equals(o); public override int GetHashCode() => base.GetHashCode(); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool operator ==(Assembly left, Assembly right) + public static bool operator ==(Assembly? left, Assembly? right) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test @@ -170,7 +166,7 @@ public override string ToString() } // Try fast reference equality and opposite null check prior to calling the slower virtual Equals - if ((object)left == (object)right) + if ((object?)left == (object)right) { return true; } @@ -178,14 +174,14 @@ public override string ToString() return (left is null) ? false : left.Equals(right); } - public static bool operator !=(Assembly left, Assembly right) + public static bool operator !=(Assembly? left, Assembly? right) { return !(left == right); } - public static string CreateQualifiedName(string assemblyName, string typeName) => typeName + ", " + assemblyName; + public static string CreateQualifiedName(string? assemblyName, string? typeName) => typeName + ", " + assemblyName; - public static Assembly GetAssembly(Type type) + public static Assembly? GetAssembly(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); @@ -199,29 +195,10 @@ public static Assembly GetAssembly(Type type) public static Assembly Load(byte[] rawAssembly) => Load(rawAssembly, rawSymbolStore: null); - [Obsolete("This method has been deprecated. Please use Assembly.Load() instead. https://go.microsoft.com/fwlink/?linkid=14202")] - public static Assembly LoadWithPartialName(string partialName) - { - if (partialName == null) - throw new ArgumentNullException(nameof(partialName)); - - if ((partialName.Length == 0) || (partialName[0] == '\0')) - throw new ArgumentException(SR.Format_StringZeroLength, nameof(partialName)); - - try - { - return Load(partialName); - } - catch (FileNotFoundException) - { - return null; - } - } - // Loads the assembly with a COFF based IMAGE containing // an emitted assembly. The assembly is loaded into a fully isolated ALC with resolution fully deferred to the AssemblyLoadContext.Default. // The second parameter is the raw bytes representing the symbol store that matches the assembly. - public static Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore) + public static Assembly Load(byte[] rawAssembly, byte[]? rawSymbolStore) { if (rawAssembly == null) throw new ArgumentNullException(nameof(rawAssembly)); @@ -271,9 +248,9 @@ public static Assembly LoadFile(string path) return result; } - private static Assembly LoadFromResolveHandler(object sender, ResolveEventArgs args) + private static Assembly? LoadFromResolveHandler(object? sender, ResolveEventArgs args) { - Assembly requestingAssembly = args.RequestingAssembly; + Assembly? requestingAssembly = args.RequestingAssembly; if (requestingAssembly == null) { return null; @@ -300,8 +277,8 @@ private static Assembly LoadFromResolveHandler(object sender, ResolveEventArgs a // Requestor assembly was loaded using loadFrom, so look for its dependencies // in the same folder as it. // Form the name of the assembly using the path of the assembly that requested its load. - AssemblyName requestedAssemblyName = new AssemblyName(args.Name); - string requestedAssemblyPath = Path.Combine(Path.GetDirectoryName(requestorPath), requestedAssemblyName.Name + ".dll"); + AssemblyName requestedAssemblyName = new AssemblyName(args.Name!); + string requestedAssemblyPath = Path.Combine(Path.GetDirectoryName(requestorPath)!, requestedAssemblyName.Name + ".dll"); try { @@ -328,7 +305,7 @@ public static Assembly LoadFrom(string assemblyFile) { if (!s_loadFromHandlerSet) { - AssemblyLoadContext.AssemblyResolve += LoadFromResolveHandler; + AssemblyLoadContext.AssemblyResolve += LoadFromResolveHandler!; s_loadFromHandlerSet = true; } } @@ -347,19 +324,19 @@ public static Assembly LoadFrom(string assemblyFile) return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath); } - public static Assembly LoadFrom(string assemblyFile, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm) + public static Assembly LoadFrom(string? assemblyFile, byte[]? hashValue, AssemblyHashAlgorithm hashAlgorithm) { throw new NotSupportedException(SR.NotSupported_AssemblyLoadFromHash); } public static Assembly UnsafeLoadFrom(string assemblyFile) => LoadFrom(assemblyFile); - public Module LoadModule(string moduleName, byte[] rawModule) => LoadModule(moduleName, rawModule, null); - public virtual Module LoadModule(string moduleName, byte[] rawModule, byte[] rawSymbolStore) { throw NotImplemented.ByDesign; } + public Module LoadModule(string? moduleName, byte[]? rawModule) => LoadModule(moduleName, rawModule, null); + public virtual Module LoadModule(string? moduleName, byte[]? rawModule, byte[]? rawSymbolStore) { throw NotImplemented.ByDesign; } - public static Assembly ReflectionOnlyLoad(byte[] rawAssembly) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } - public static Assembly ReflectionOnlyLoad(string assemblyString) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } - public static Assembly ReflectionOnlyLoadFrom(string assemblyFile) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } + public static Assembly ReflectionOnlyLoad(byte[]? rawAssembly) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } + public static Assembly ReflectionOnlyLoad(string? assemblyString) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } + public static Assembly ReflectionOnlyLoadFrom(string? assemblyFile) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } public virtual SecurityRuleSet SecurityRuleSet => SecurityRuleSet.None; } diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyAlgorithmIdAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyAlgorithmIdAttribute.cs index df91553db0b2..fe24f353beb1 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyAlgorithmIdAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyAlgorithmIdAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Configuration.Assemblies; namespace System.Reflection diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyCompanyAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyCompanyAttribute.cs index c1e7a82c578d..d986db60a341 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyCompanyAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyCompanyAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyConfigurationAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyConfigurationAttribute.cs index 4c6d367dace8..195c4d0ca60d 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyConfigurationAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyConfigurationAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyContentType.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyContentType.cs index 938ac26d653e..2ee1a008181c 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyContentType.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyContentType.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { public enum AssemblyContentType diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyCopyrightAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyCopyrightAttribute.cs index fe06a4f5cc79..e50e19932b9b 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyCopyrightAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyCopyrightAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyCultureAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyCultureAttribute.cs index ee70784873b7..e31c6f9c1cbd 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyCultureAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyCultureAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyDelaySignAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyDelaySignAttribute.cs index 02acff9ed3a0..eae2cf613c7c 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyDelaySignAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyDelaySignAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyDescriptionAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyDescriptionAttribute.cs index 4348a78698cd..50f57c96a659 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyDescriptionAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyDescriptionAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyFileVersionAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyFileVersionAttribute.cs index 2bd76ceaa64c..b5b52c1897fc 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyFileVersionAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyFileVersionAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyFlagsAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyFlagsAttribute.cs index 6520831aa726..be35bc028933 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyFlagsAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyFlagsAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyInformationalVersionAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyInformationalVersionAttribute.cs index 29384a84517e..915b973ab94e 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyInformationalVersionAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyInformationalVersionAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyKeyFileAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyKeyFileAttribute.cs index 5bfcb170a404..9f7387d8af06 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyKeyFileAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyKeyFileAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyKeyNameAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyKeyNameAttribute.cs index 4a1dc4eb5969..4cf51754eaf2 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyKeyNameAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyKeyNameAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyMetadataAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyMetadataAttribute.cs index 3ca34e81fb33..be85ac48b77d 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyMetadataAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyMetadataAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyName.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyName.cs index 37d08e673912..ffdac5666525 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyName.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyName.cs @@ -14,14 +14,14 @@ public sealed partial class AssemblyName : ICloneable, IDeserializationCallback, { // If you modify any of these fields, you must also update the // AssemblyBaseObject structure in object.h - private string _name; - private byte[] _publicKey; - private byte[] _publicKeyToken; - private CultureInfo _cultureInfo; - private string _codeBase; - private Version _version; + private string? _name; + private byte[]? _publicKey; + private byte[]? _publicKeyToken; + private CultureInfo? _cultureInfo; + private string? _codeBase; + private Version? _version; - private StrongNameKeyPair _strongNameKeyPair; + private StrongNameKeyPair? _strongNameKeyPair; private AssemblyHashAlgorithm _hashAlgorithm; @@ -36,26 +36,26 @@ public AssemblyName() // Set and get the name of the assembly. If this is a weak Name // then it optionally contains a site. For strong assembly names, // the name partitions up the strong name's namespace - public string Name + public string? Name { get { return _name; } set { _name = value; } } - public Version Version + public Version? Version { get { return _version; } set { _version = value; } } // Locales, internally the LCID is used for the match. - public CultureInfo CultureInfo + public CultureInfo? CultureInfo { get { return _cultureInfo; } set { _cultureInfo = value; } } - public string CultureName + public string? CultureName { get { @@ -67,13 +67,13 @@ public string CultureName } } - public string CodeBase + public string? CodeBase { get { return _codeBase; } set { _codeBase = value; } } - public string EscapedCodeBase + public string? EscapedCodeBase { get { @@ -155,12 +155,12 @@ public static AssemblyName GetAssemblyName(string assemblyFile) return GetFileInformationCore(assemblyFile); } - public byte[] GetPublicKey() + public byte[]? GetPublicKey() { return _publicKey; } - public void SetPublicKey(byte[] publicKey) + public void SetPublicKey(byte[]? publicKey) { _publicKey = publicKey; @@ -179,7 +179,7 @@ public byte[] GetPublicKeyToken() return _publicKeyToken; } - public void SetPublicKeyToken(byte[] publicKeyToken) + public void SetPublicKeyToken(byte[]? publicKeyToken) { _publicKeyToken = publicKeyToken; } @@ -213,7 +213,7 @@ public AssemblyVersionCompatibility VersionCompatibility set { _versionCompatibility = value; } } - public StrongNameKeyPair KeyPair + public StrongNameKeyPair? KeyPair { get { return _strongNameKeyPair; } set { _strongNameKeyPair = value; } @@ -235,7 +235,7 @@ public override string ToString() { string s = FullName; if (s == null) - return base.ToString(); + return base.ToString()!; else return s; } @@ -255,7 +255,7 @@ public void OnDeserialization(object sender) /// match the intent of this api, this api has been broken this way since its debut and we cannot /// change its behavior now. /// - public static bool ReferenceMatchesDefinition(AssemblyName reference, AssemblyName definition) + public static bool ReferenceMatchesDefinition(AssemblyName? reference, AssemblyName? definition) { if (object.ReferenceEquals(reference, definition)) return true; @@ -271,13 +271,13 @@ public static bool ReferenceMatchesDefinition(AssemblyName reference, AssemblyNa return refName.Equals(defName, StringComparison.OrdinalIgnoreCase); } - internal static string EscapeCodeBase(string codebase) + internal static string EscapeCodeBase(string? codebase) { if (codebase == null) return string.Empty; int position = 0; - char[] dest = EscapeString(codebase, 0, codebase.Length, null, ref position, true, c_DummyChar, c_DummyChar, c_DummyChar); + char[]? dest = EscapeString(codebase, 0, codebase.Length, null, ref position, true, c_DummyChar, c_DummyChar, c_DummyChar); if (dest == null) return codebase; @@ -296,7 +296,7 @@ internal static string EscapeCodeBase(string codebase) // // Returns null if nothing has to be escaped AND passed dest was null, otherwise the resulting array with the updated destPos // - internal static unsafe char[] EscapeString(string input, int start, int end, char[] dest, ref int destPos, + internal static unsafe char[]? EscapeString(string input, int start, int end, char[]? dest, ref int destPos, bool isUriString, char force1, char force2, char rsvd) { int i = start; @@ -397,15 +397,15 @@ internal static unsafe char[] EscapeString(string input, int start, int end, cha // // ensure destination array has enough space and contains all the needed input stuff // - private static unsafe char[] EnsureDestinationSize(char* pStr, char[] dest, int currentInputPos, + private static unsafe char[] EnsureDestinationSize(char* pStr, char[]? dest, int currentInputPos, short charsToAdd, short minReallocateChars, ref int destPos, int prevInputPos) { - if ((object)dest == null || dest.Length < destPos + (currentInputPos - prevInputPos) + charsToAdd) + if (dest is null || dest.Length < destPos + (currentInputPos - prevInputPos) + charsToAdd) { // allocating or reallocating array by ensuring enough space based on maxCharsToAdd. char[] newresult = new char[destPos + (currentInputPos - prevInputPos) + minReallocateChars]; - if ((object)dest != null && destPos != 0) + if (!(dest is null) && destPos != 0) Buffer.BlockCopy(dest, 0, newresult, 0, destPos << 1); dest = newresult; } diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyNameFlags.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyNameFlags.cs index 82f64c160aab..d32103203142 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyNameFlags.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyNameFlags.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [Flags] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyNameFormatter.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyNameFormatter.cs index 90ccd1fe5431..02f1752074f7 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyNameFormatter.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyNameFormatter.cs @@ -11,7 +11,7 @@ namespace System.Reflection { internal static class AssemblyNameFormatter { - public static string ComputeDisplayName(string name, Version version, string cultureName, byte[] pkt, AssemblyNameFlags flags, AssemblyContentType contentType) + public static string ComputeDisplayName(string? name, Version? version, string? cultureName, byte[]? pkt, AssemblyNameFlags flags, AssemblyContentType contentType) { const int PUBLIC_KEY_TOKEN_LEN = 8; diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyProductAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyProductAttribute.cs index 9966d603cb46..43cb62df9978 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyProductAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyProductAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblySignatureKeyAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblySignatureKeyAttribute.cs index 8410b4f60267..e6ec8af1b389 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblySignatureKeyAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblySignatureKeyAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyTitleAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyTitleAttribute.cs index d03dad6440ac..26d7a2e66c0e 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyTitleAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyTitleAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyTrademarkAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyTrademarkAttribute.cs index 5b373193f6f3..1d3edf51d585 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyTrademarkAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyTrademarkAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/AssemblyVersionAttribute.cs b/src/Common/src/CoreLib/System/Reflection/AssemblyVersionAttribute.cs index 9cba8e3f9af4..b3557bac9739 100644 --- a/src/Common/src/CoreLib/System/Reflection/AssemblyVersionAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/AssemblyVersionAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/Common/src/CoreLib/System/Reflection/Binder.cs b/src/Common/src/CoreLib/System/Reflection/Binder.cs index 3dc5665d520f..0784db0eee92 100644 --- a/src/Common/src/CoreLib/System/Reflection/Binder.cs +++ b/src/Common/src/CoreLib/System/Reflection/Binder.cs @@ -9,11 +9,11 @@ namespace System.Reflection public abstract class Binder { protected Binder() { } - public abstract FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture); - public abstract MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state); - public abstract object ChangeType(object value, Type type, CultureInfo culture); + public abstract FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo? culture); + public abstract MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object?[] args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? names, out object? state); + public abstract object ChangeType(object value, Type type, CultureInfo? culture); public abstract void ReorderArgumentArray(ref object[] args, object state); - public abstract MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers); - public abstract PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers); + public abstract MethodBase? SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[]? modifiers); + public abstract PropertyInfo? SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type? returnType, Type[]? indexes, ParameterModifier[]? modifiers); } } diff --git a/src/Common/src/CoreLib/System/Reflection/BindingFlags.cs b/src/Common/src/CoreLib/System/Reflection/BindingFlags.cs index ac64814edd08..7ba83e20da63 100644 --- a/src/Common/src/CoreLib/System/Reflection/BindingFlags.cs +++ b/src/Common/src/CoreLib/System/Reflection/BindingFlags.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [Flags] diff --git a/src/Common/src/CoreLib/System/Reflection/CallingConventions.cs b/src/Common/src/CoreLib/System/Reflection/CallingConventions.cs index 3bd060769bec..bb6d6cd80944 100644 --- a/src/Common/src/CoreLib/System/Reflection/CallingConventions.cs +++ b/src/Common/src/CoreLib/System/Reflection/CallingConventions.cs @@ -4,7 +4,6 @@ // CallingConventions is a set of Bits representing the calling conventions in the system. -#nullable enable namespace System.Reflection { [Flags] diff --git a/src/Common/src/CoreLib/System/Reflection/ConstructorInfo.cs b/src/Common/src/CoreLib/System/Reflection/ConstructorInfo.cs index 1e31194cfcad..8b376025659f 100644 --- a/src/Common/src/CoreLib/System/Reflection/ConstructorInfo.cs +++ b/src/Common/src/CoreLib/System/Reflection/ConstructorInfo.cs @@ -16,14 +16,14 @@ protected ConstructorInfo() { } [DebuggerHidden] [DebuggerStepThrough] - public object Invoke(object[] parameters) => Invoke(BindingFlags.Default, binder: null, parameters: parameters, culture: null); - public abstract object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture); + public object Invoke(object?[]? parameters) => Invoke(BindingFlags.Default, binder: null, parameters: parameters, culture: null); + public abstract object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture); - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object? obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool operator ==(ConstructorInfo left, ConstructorInfo right) + public static bool operator ==(ConstructorInfo? left, ConstructorInfo? right) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test @@ -34,7 +34,7 @@ protected ConstructorInfo() { } } // Try fast reference equality and opposite null check prior to calling the slower virtual Equals - if ((object)left == (object)right) + if ((object?)left == (object)right) { return true; } @@ -42,7 +42,7 @@ protected ConstructorInfo() { } return (left is null) ? false : left.Equals(right); } - public static bool operator !=(ConstructorInfo left, ConstructorInfo right) => !(left == right); + public static bool operator !=(ConstructorInfo? left, ConstructorInfo? right) => !(left == right); public static readonly string ConstructorName = ".ctor"; public static readonly string TypeConstructorName = ".cctor"; diff --git a/src/Common/src/CoreLib/System/Reflection/CorElementType.cs b/src/Common/src/CoreLib/System/Reflection/CorElementType.cs index b6968f1f11d5..37ffcfa1e254 100644 --- a/src/Common/src/CoreLib/System/Reflection/CorElementType.cs +++ b/src/Common/src/CoreLib/System/Reflection/CorElementType.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { internal enum CorElementType : byte diff --git a/src/Common/src/CoreLib/System/Reflection/CustomAttributeFormatException.cs b/src/Common/src/CoreLib/System/Reflection/CustomAttributeFormatException.cs index 0d38eaaebcc5..8bdfb3e5d508 100644 --- a/src/Common/src/CoreLib/System/Reflection/CustomAttributeFormatException.cs +++ b/src/Common/src/CoreLib/System/Reflection/CustomAttributeFormatException.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable using System.Runtime.Serialization; namespace System.Reflection diff --git a/src/Common/src/CoreLib/System/Reflection/DefaultMemberAttribute.cs b/src/Common/src/CoreLib/System/Reflection/DefaultMemberAttribute.cs index 0667d34878d7..585fdb07cd0f 100644 --- a/src/Common/src/CoreLib/System/Reflection/DefaultMemberAttribute.cs +++ b/src/Common/src/CoreLib/System/Reflection/DefaultMemberAttribute.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] diff --git a/src/Common/src/CoreLib/System/Reflection/Emit/AssemblyBuilderAccess.cs b/src/Common/src/CoreLib/System/Reflection/Emit/AssemblyBuilderAccess.cs index baac3a7a4101..8527463eec89 100644 --- a/src/Common/src/CoreLib/System/Reflection/Emit/AssemblyBuilderAccess.cs +++ b/src/Common/src/CoreLib/System/Reflection/Emit/AssemblyBuilderAccess.cs @@ -5,7 +5,6 @@ // This enumeration defines the access modes for a dynamic assembly. // EE uses these enum values..look for m_dwDynamicAssemblyAccess in Assembly.hpp -#nullable enable namespace System.Reflection.Emit { [Flags] diff --git a/src/Common/src/CoreLib/System/Reflection/Emit/EventToken.cs b/src/Common/src/CoreLib/System/Reflection/Emit/EventToken.cs index 85c917864f7a..302ea5653ba1 100644 --- a/src/Common/src/CoreLib/System/Reflection/Emit/EventToken.cs +++ b/src/Common/src/CoreLib/System/Reflection/Emit/EventToken.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection.Emit { public struct EventToken diff --git a/src/Common/src/CoreLib/System/Reflection/Emit/FieldToken.cs b/src/Common/src/CoreLib/System/Reflection/Emit/FieldToken.cs index e0aba63ba134..cf11b8b6e679 100644 --- a/src/Common/src/CoreLib/System/Reflection/Emit/FieldToken.cs +++ b/src/Common/src/CoreLib/System/Reflection/Emit/FieldToken.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable enable namespace System.Reflection.Emit { /// diff --git a/src/Common/src/CoreLib/System/Reflection/Emit/FlowControl.cs b/src/Common/src/CoreLib/System/Reflection/Emit/FlowControl.cs index 0410cc915f40..9cb947ce5a92 100644 --- a/src/Common/src/CoreLib/System/Reflection/Emit/FlowControl.cs +++ b/src/Common/src/CoreLib/System/Reflection/Emit/FlowControl.cs @@ -12,7 +12,6 @@ ** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.** ==============================================================*/ -#nullable enable namespace System.Reflection.Emit { public enum FlowControl diff --git a/src/Common/src/CoreLib/System/Reflection/Emit/Label.cs b/src/Common/src/CoreLib/System/Reflection/Emit/Label.cs index 4aa5e7c9596b..b3cacf5d434f 100644 --- a/src/Common/src/CoreLib/System/Reflection/Emit/Label.cs +++ b/src/Common/src/CoreLib/System/Reflection/Emit/Label.cs @@ -14,7 +14,6 @@ ** ===========================================================*/ -#nullable enable namespace System.Reflection.Emit { // The Label class is an opaque representation of a label used by the @@ -23,9 +22,9 @@ namespace System.Reflection.Emit // is passed to the MethodWriter. // Labels are created by using ILGenerator.CreateLabel and their position is set // by using ILGenerator.MarkLabel. - public struct Label : IEquatable