diff --git a/.vsts-ci.yml b/.vsts-ci.yml index 6a435a3f0..5fcaedd61 100644 --- a/.vsts-ci.yml +++ b/.vsts-ci.yml @@ -1,37 +1,164 @@ jobs: + - job: build + strategy: + matrix: + linux: + osName: 'Linux' + imageName: 'ubuntu-22.04' + mac: + osName: 'macOS' + imageName: 'macOS-latest' + windows: + osName: 'Windows' + imageName: 'windows-latest' -################################################################################ -- job: Windows -################################################################################ - displayName: Windows - timeoutInMinutes: 180 - pool: - vmImage: windows-latest - steps: - - template: eng/steps.yml - parameters: - os: 'Windows' - -################################################################################ -- job: Linux -################################################################################ - displayName: Linux (Ubuntu) - timeoutInMinutes: 180 - pool: - vmImage: ubuntu-22.04 - steps: - - template: eng/steps.yml - parameters: - os: 'Linux' - -################################################################################ -- job: macOS -################################################################################ - displayName: macOS - timeoutInMinutes: 180 - pool: - vmImage: macOS-latest - steps: - - template: eng/steps.yml - parameters: - os: 'macOS' + displayName: Build + timeoutInMinutes: 180 + pool: + vmImage: $(imageName) + + steps: + # Prerequisites + - checkout: self + submodules: true + + - task: Bash@3 + displayName: Install tools + inputs: + targetType: inline + script: | + sudo apt-get -yq install dos2unix + condition: eq(variables.osName, 'Linux') + + # Setup .NET + - task: UseDotNet@2 + displayName: Install .NET 9.0 SDK for build + inputs: + packageType: 'sdk' + version: '9.0.x' + + # Display version info + - task: PowerShell@2 + displayName: Version Information + inputs: + targetType: inline + script: | + dotnet --info + try { msbuild -version } catch { } + try { mono --version } catch { } + + # Build & Package + - powershell: ./make.ps1 + displayName: Build + + - powershell: ./make.ps1 package + displayName: Package + + - task: CopyFiles@2 + displayName: Copy Build Logs + inputs: + Contents: '*.binlog' + TargetFolder: '$(Build.ArtifactStagingDirectory)' + condition: and(succeededOrFailed(), eq(variables['system.pullrequest.isfork'], false)) + + - task: CopyFiles@2 + displayName: Copy Packages + inputs: + SourceFolder: '$(Build.Repository.LocalPath)/Package/Release/Packages' + Contents: | + **/*.nupkg + **/*.snupkg + **/*.zip + **/*.msi + **/*.deb + **/*.pkg + TargetFolder: '$(Build.ArtifactStagingDirectory)' + condition: and(succeededOrFailed(), eq(variables['system.pullrequest.isfork'], false)) + + - task: PublishBuildArtifacts@1 + displayName: Publish Artifacts + inputs: + ArtifactName: '$(osName) Artifacts' + condition: and(succeededOrFailed(), eq(variables['system.pullrequest.isfork'], false)) + + - job: test + strategy: + matrix: + linux_net462: + osName: Linux + imageName: ubuntu-22.04 + framework: net462 + linux_net6_0: + osName: Linux + imageName: ubuntu-22.04 + framework: net6.0 + linux_net8_0: + osName: Linux + imageName: ubuntu-22.04 + framework: net8.0 + macos_net462: + osName: macOS + imageName: macOS-latest + framework: net462 + macos_net6_0: + osName: macOS + imageName: macOS-latest + framework: net6.0 + macos_net8_0: + osName: macOS + imageName: macOS-latest + framework: net8.0 + windows_net462: + osName: Windows + imageName: windows-latest + framework: net462 + windows_net6_0: + osName: Windows + imageName: windows-latest + framework: net6.0 + windows_net8_0: + osName: Windows + imageName: windows-latest + framework: net8.0 + + displayName: Test + timeoutInMinutes: 180 + pool: + vmImage: $(imageName) + + steps: + # Prerequisites + - checkout: self + submodules: true + + # Setup .NET + - task: UseDotNet@2 + displayName: Install .NET 6.0 runtime for testing + inputs: + packageType: 'runtime' + version: '6.0.x' + - task: UseDotNet@2 + displayName: Install .NET 8.0 runtime for testing + inputs: + packageType: 'runtime' + version: '8.0.x' + - task: UseDotNet@2 + displayName: Install .NET 9.0 SDK for build + inputs: + packageType: 'sdk' + version: '9.0.x' + + # Build & Test + - powershell: ./make.ps1 + displayName: Build + - powershell: ./make.ps1 -frameworks $(framework) test-all + displayName: Test ($(framework)) + + - task: PublishTestResults@2 + displayName: Publish Test Results + inputs: + testRunner: VSTest + testResultsFiles: '**/*.trx' + mergeTestResults: true + testRunTitle: $(osName) - $(framework) + condition: succeededOrFailed() diff --git a/Directory.Build.props b/Directory.Build.props index 2beab9202..bfbb339eb 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -27,6 +27,9 @@ $(MajorVersion).$(MinorVersion).$(MicroVersion).$(AssemblyFileRevision) $(MSBuildProjectName) $(MajorVersion).$(MinorVersion).$(MicroVersion) $(ReleaseLevel) $(ReleaseSerial) + PYTHON_$(MajorVersion)$(MinorVersion) + $(PythonSymbols);PYTHON_36_OR_GREATER + false false @@ -125,7 +128,7 @@ portable true false - $(Features);$(SignedSym);TRACE + $(PythonSymbols);$(Features);$(SignedSym);TRACE @@ -135,6 +138,6 @@ false false - $(Features);$(SignedSym);DEBUG;TRACE + $(PythonSymbols);$(Features);$(SignedSym);DEBUG;TRACE diff --git a/IronPython.sln b/IronPython.sln index 6a760c366..2a77b6b94 100644 --- a/IronPython.sln +++ b/IronPython.sln @@ -42,7 +42,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{17737ACB eng\net9.0-windows.props = eng\net9.0-windows.props eng\net9.0.props = eng\net9.0.props eng\netstandard2.0.props = eng\netstandard2.0.props - eng\steps.yml = eng\steps.yml eng\Tasks.Targets = eng\Tasks.Targets EndProjectSection EndProject diff --git a/README.md b/README.md index 01e8c89da..44353a451 100644 --- a/README.md +++ b/README.md @@ -12,12 +12,14 @@ IronPython 3 targets Python 3, including the re-organized standard library, Unic | **What?** | **Where?** | | --------: | :------------: | | **Windows/Linux/macOS Builds** | [![Build status](https://dotnet.visualstudio.com/IronLanguages/_apis/build/status/ironpython3)](https://dotnet.visualstudio.com/IronLanguages/_build/latest?definitionId=43) [![Github build status](https://github.com/IronLanguages/ironpython3/workflows/CI/badge.svg)](https://github.com/IronLanguages/ironpython3/actions?workflow=CI) | -| **Downloads** | [![NuGet](https://img.shields.io/nuget/vpre/IronPython.svg)](https://www.nuget.org/packages/IronPython/3.4.0) [![Release](https://img.shields.io/github/release/IronLanguages/ironpython3.svg?include_prereleases)](https://github.com/IronLanguages/ironpython3/releases/latest)| +| **Downloads** | [![NuGet](https://img.shields.io/nuget/vpre/IronPython.svg)](https://www.nuget.org/packages/IronPython/latest) [![Release](https://img.shields.io/github/release/IronLanguages/ironpython3.svg?include_prereleases)](https://github.com/IronLanguages/ironpython3/releases/latest)| | **Help** | [![Gitter chat](https://badges.gitter.im/IronLanguages/ironpython.svg)](https://gitter.im/IronLanguages/ironpython) [![StackExchange](https://img.shields.io/badge/stack%20overflow-ironpython-informational?logo=stack-overflow&logoColor=white)](https://stackoverflow.com/questions/tagged/ironpython) | ## Examples +To see how to use in PowerShell (either directly embedded or executable invocation), skip to [Installation](#Installation) + The following C# program: ```cs @@ -87,7 +89,62 @@ See the [Package compatibility](https://github.com/IronLanguages/ironpython3/wik ## Installation -Binaries of IronPython 3 can be downloaded from the [release page](https://github.com/IronLanguages/ironpython3/releases/latest), available in various formats: `.msi`, `.zip`, `.deb`, `.pkg`. The IronPython package is also available on [NuGet](https://www.nuget.org/packages/IronPython/3.4.0). See the [installation document](https://github.com/IronLanguages/ironpython3/wiki/Installing) for detailed instructions on how to install a standalone IronPython interpreter on various operating systems and .NET frameworks. +Binaries of IronPython 3 can be downloaded from the [release page](https://github.com/IronLanguages/ironpython3/releases/latest), available in various formats: `.msi`, `.zip`, `.deb`, `.pkg`. The IronPython package is also available on [NuGet](https://www.nuget.org/packages/IronPython/latest). See the [installation document](https://github.com/IronLanguages/ironpython3/wiki/Installing) for detailed instructions on how to install a standalone IronPython interpreter on various operating systems and .NET frameworks. + +### PowerShell + +For usage in PowerShell, you can install using the Install-IronPython.ps1 within the aforementioned `.zip` file or by simply using this one-liner: + +```pwsh +& ([scriptblock]::Create((iwr ` + -Uri 'https://raw.githubusercontent.com/IronLanguages/ironpython3/main/eng/scripts/Install-IronPython.ps1').Content)) ` + -Path "~/ipyenv/v3.4.2" + +# Optionally, ensure pip: +# & "~/ipyenv/v3.4.2/ipy" -m ensurepip +``` + +Once installed, you can start using IronPython directly in PowerShell! + +To use the ipy shim, you can use: +```pwsh +& "~/ipyenv/v3.4.2/Enter-IronPythonEnvironment.ps1" + +ipy -c "print('Hello from IronPython!')" +``` + +... or to use IronPython embedded in PowerShell, you can use: +```pwsh +Import-Module "~/ipyenv/v3.4.2/IronPython.dll" + +$engine = & { + $engine = [IronPython.Hosting.Python]::CreateEngine() + + # You need to add the correct paths, as IronPython will use PowerShell's installation path by default + $paths = $engine.GetSearchPaths() + $paths.Add("$(Resolve-Path "~/ipyenv/v3.4.2/lib")") + $paths.Add("$(Resolve-Path "~/ipyenv/v3.4.2/lib/site-packages")") + + # To use `wpf` and `sqlite3` you have to add the DLLs search path + # - the [IronPython.SQLite] and [IronPython.WPF] powershell namespaces will become available on python import + $paths.Add("$(Resolve-Path "~/ipyenv/v3.4.2/DLLs")") + + # or if you prefer to have the powershell namespaces early, you can use: + # - just note, you will have to initialize _sqlite3 (see further down the script) + # Import-Module "~/ipyenv/v3.4.2/DLLs/IronPython.SQLite.dll" + # Import-Module "~/ipyenv/v3.4.2/DLLs/IronPython.WPF.dll" + + $engine.SetSearchPaths($paths) + + # Then have fun! + $engine.Execute("print('Hello from IronPython!')") + + # Optionally, if you need to initialize _sqlite3: + # $engine.Execute("import sqlite3") + + return $engine +} +``` ## Build diff --git a/eng/scripts/Install-IronPython.ps1 b/eng/scripts/Install-IronPython.ps1 index c231142ec..3ccc58af7 100755 --- a/eng/scripts/Install-IronPython.ps1 +++ b/eng/scripts/Install-IronPython.ps1 @@ -12,18 +12,26 @@ .EXAMPLE - PS>Invoke-WebRequest -Uri https://github.com/IronLanguages/ironpython3/releases/download/v3.4.0/IronPython.3.4.0.zip -OutFile IronPython.3.4.0.zip - PS>Expand-Archive -Path IronPython.3.4.0.zip -DestinationPath IronPython-unzipped - PS>./IronPython-unzipped/scripts/Install-IronPython -Path ~/ipyenv/v3.4.0 + With a one-liner, install latest over the web: - The official binaries are downloaded from GitHub to the current directory, unzipped, and then the installation proceeds using the script from the unzipped directory. IronPython is installed into ~/ipyenv/v3.4.0. + PS>& ([scriptblock]::Create((iwr 'https://raw.githubusercontent.com/IronLanguages/ironpython3/main/eng/scripts/Install-IronPython.ps1').Content)) -Path ~/ipyenv/v3.4.2 + + The official binaries are downloaded from GitHub to the current directory, unzipped, and then the installation proceeds using the script from the unzipped directory. IronPython is installed into ~/ipyenv/v3.4.2 + +.EXAMPLE + + PS>Invoke-WebRequest -Uri https://github.com/IronLanguages/ironpython3/releases/download/v3.4.2/IronPython.3.4.2.zip -OutFile IronPython.3.4.2.zip + PS>Expand-Archive -Path IronPython.3.4.2.zip -DestinationPath IronPython-unzipped + PS>./IronPython-unzipped/scripts/Install-IronPython -Path ~/ipyenv/v3.4.2 + + The official binaries are downloaded from GitHub to the current directory, unzipped, and then the installation proceeds using the script from the unzipped directory. IronPython is installed into ~/ipyenv/v3.4.2 .EXAMPLE - PS>Invoke-WebRequest -Uri https://github.com/IronLanguages/ironpython3/releases/download/v3.4.0/IronPython.3.4.0.zip -OutFile IronPython.3.4.0.zip - PS>Install-IronPython -Path ~/ipyenv/v3.4.0 -ZipFile IronPython.3.4.0.zip -Framework net462 -Force + PS>Invoke-WebRequest -Uri https://github.com/IronLanguages/ironpython3/releases/download/v3.4.2/IronPython.3.4.2.zip -OutFile IronPython.3.4.2.zip + PS>Install-IronPython -Path ~/ipyenv/v3.4.2 -ZipFile IronPython.3.4.2.zip -Framework net462 -Force - The official binaries are downloaded from GitHub to the current directory and then the installation proceeds using the downloaded zip file. IronPython is installed into ~/ipyenv/v3.4.0, overwriting any previous installation in that location. IronPython binaries running on .NET Framework 4.6.2 are used during the installation. + The official binaries are downloaded from GitHub to the current directory and then the installation proceeds using the downloaded zip file. IronPython is installed into ~/ipyenv/v3.4.2, overwriting any previous installation in that location. IronPython binaries running on .NET Framework 4.6.2 are used during the installation. This example assumes that the installation script is in a directory on the search path ($env:PATH). .EXAMPLE @@ -54,6 +62,8 @@ Param( $ErrorActionPreference = "Stop" +$downloaded = $false + if (-not $ZipFile) { # If zipfile path not given, try to locate it $splitPSScriptRoot = $PSScriptRoot -split "\$([IO.Path]::DirectorySeparatorChar)" @@ -72,7 +82,23 @@ if (-not $ZipFile) { } $ZipFile = $zipFiles } else { - Write-Error "Cannot locate implicit zip file. Provide path to the zip file using '-ZipFile '." + Try { + $zipUrl = (Invoke-RestMethod "https://api.github.com/repos/IronLanguages/ironpython3/releases/latest").assets | + Where-Object -Property name -Like "IronPython.3.*.zip" | + Select-Object -ExpandProperty browser_download_url + + $downloadPath = "$([System.IO.Path]::GetTempPath())$([guid]::NewGuid()).zip" + Invoke-WebRequest -Uri $zipUrl -OutFile $downloadPath | Out-Null + + if (-not (Test-Path -PathType Leaf $downloadPath)) { + throw + } + + $downloaded = $true + $ZipFile = $downloadPath + } Catch { + Write-Error "Cannot retrieve zip file implicitly. Check your network connection or provide a path to the zip file using '-ZipFile '." + } } } elseif (-not (Test-Path $ZipFile)) { Write-Error "ZipFile not found: $ZipFile" @@ -85,16 +111,24 @@ if (Test-Path $Path) { Write-Error "Overwriting of multiple destinations not allowed: $Path" } Remove-Item -Path $Path -Force -Recurse + New-Item $Path -ItemType Directory | Out-Null } else { - Write-Error "Path already exists: $Path" + Write-Warning "Path already exists: $(Resolve-Path $Path)" } +} else { + New-Item $Path -ItemType Directory | Out-Null } -New-Item $Path -ItemType Directory | Out-Null # Unzip archive if (-not $unzipDir) { $unzipDir = Join-Path $Path "unzipped" Expand-Archive -Path $ZipFile -DestinationPath $unzipDir + + # Cleanup temporary files + if ($downloaded) { + Remove-Item -Path $ZipFile + } + $unzipped = $true } diff --git a/eng/scripts/generate_exceptions.py b/eng/scripts/generate_exceptions.py index 9ce1294f2..563f35dfe 100644 --- a/eng/scripts/generate_exceptions.py +++ b/eng/scripts/generate_exceptions.py @@ -265,7 +265,7 @@ def get_clr_name(e): return e.replace('Error', '') + 'Exception' FACTORY = """ -public static Exception %(name)s(string format, params object[] args) { +public static Exception %(name)s(string format, params object?[] args) { return new %(clrname)s(string.Format(format, args)); }""" diff --git a/eng/scripts/generate_typecache.py b/eng/scripts/generate_typecache.py index 32eca2a36..2e53ddacf 100644 --- a/eng/scripts/generate_typecache.py +++ b/eng/scripts/generate_typecache.py @@ -74,21 +74,15 @@ def gen_typecache_storage(cw): types[x.typeType] = [x] for type in types: for a_type in types[type]: - cw.write('private static %s %s;' % (type, a_type.name)) + cw.write('private static %s? %s;' % (type, a_type.name)) # outputs the public getters for each cached type def gen_typecache(cw): for x in data: - cw.enter_block("public static %s %s" % (x.typeType, x.entryName)) - cw.enter_block("get") - - if x.typeType != 'PythonType': cast = '(%s)' % x.typeType - else: cast = "" - - cw.write("if (%s == null) %s = %sDynamicHelpers.GetPythonTypeFromType(typeof(%s));" % (x.name, x.name, cast, x.type)) - cw.write("return %s;" % x.name) - cw.exit_block() - cw.exit_block() + cw.write("public static %s %s" % (x.typeType, x.entryName)) + cw.indent() + cw.write("=> %s ??= DynamicHelpers.GetPythonTypeFromType(typeof(%s));" % (x.name, x.type)) + cw.dedent() cw.write("") def main(): diff --git a/eng/steps.yml b/eng/steps.yml deleted file mode 100644 index 5903af548..000000000 --- a/eng/steps.yml +++ /dev/null @@ -1,146 +0,0 @@ -parameters: - os: '' - -steps: - - checkout: self - submodules: true - - - powershell: | - - $xml = [xml] (Get-Content CurrentVersion.props) - $major = $xml.Project.PropertyGroup.MajorVersion - $minor = $xml.Project.PropertyGroup.MinorVersion - $micro = $xml.Project.PropertyGroup.MicroVersion - $serial = $xml.Project.PropertyGroup.ReleaseSerial - $level = $xml.Project.PropertyGroup.ReleaseLevel - - if($level -eq 'final') { - $PackageVersion = "$major.$minor.$micro" - } elseif($level -ne 'final' -or $serial -ne '0') { - $PackageVersion = "$major.$minor.$micro-$level$serial" - } - - # store the package version to an environment variable - Write-Host ("##vso[task.setvariable variable=PackageVersion;isSecret=false;isOutput=true;]$PackageVersion") - displayName: Grab Package Version - - - task: UseDotNet@2 - displayName: Install .NET 6.0 runtime for testing - inputs: - packageType: 'runtime' - version: '6.0.x' - - - task: UseDotNet@2 - displayName: Install .NET 8.0 runtime for testing - inputs: - packageType: 'runtime' - version: '8.0.x' - - - task: UseDotNet@2 - displayName: Install .NET 9.0 SDK for build - inputs: - packageType: 'sdk' - version: '9.0.x' - - # Set Mono version on macOS - - ${{ if eq(parameters.os, 'macOS') }}: - - task: Bash@3 - displayName: Set Mono Version - inputs: - targetType: inline - script: | - # use Mono 6.4.0 version - SYMLINK=6.4.0 - MONOPREFIX=/Library/Frameworks/Mono.framework/Versions/$SYMLINK - echo "##vso[task.setvariable variable=DYLD_FALLBACK_LIBRARY_PATH;]$MONOPREFIX/lib:/lib:/usr/lib:$DYLD_LIBRARY_FALLBACK_PATH" - echo "##vso[task.setvariable variable=PKG_CONFIG_PATH;]$MONOPREFIX/lib/pkgconfig:$MONOPREFIX/share/pkgconfig:$PKG_CONFIG_PATH" - echo "##vso[task.setvariable variable=PATH;]$MONOPREFIX/bin:$PATH" - - # Install mono when running on Linux - - ${{ if eq(parameters.os, 'Linux') }}: - - task: Bash@3 - displayName: Install tools - inputs: - targetType: inline - script: | - sudo apt-get -yq install mono-vbnc dos2unix - - # Dump version info - - task: PowerShell@2 - displayName: Version Information - inputs: - targetType: inline - script: | - dotnet --info - try { msbuild -version } catch { } - try { mono --version } catch { } - - - powershell: ./make.ps1 - displayName: Build - - - powershell: ./make.ps1 test-all - displayName: Test - - - task: PublishTestResults@2 - displayName: Publish Test Results - inputs: - testRunner: VSTest - testResultsFiles: '**/*.trx' - mergeTestResults: true - testRunTitle: ${{ parameters.os }} - condition: succeededOrFailed() - - - powershell: ./make.ps1 package - displayName: Package - condition: succeededOrFailed() - - - task: CopyFiles@2 - displayName: Copy NuGet and Zip Packages - inputs: - SourceFolder: '$(Build.Repository.LocalPath)/Package/Release/Packages' - Contents: | - **/*.nupkg - **/*.snupkg - **/*.zip - TargetFolder: '$(Build.ArtifactStagingDirectory)' - condition: and(succeededOrFailed(), eq(variables['system.pullrequest.isfork'], false)) - - - ${{ if eq(parameters.os, 'Windows') }}: - - task: CopyFiles@2 - displayName: Copy MSI Installer - inputs: - SourceFolder: '$(Build.Repository.LocalPath)/Package/Release/Packages' - Contents: '**/*.msi' - TargetFolder: '$(Build.ArtifactStagingDirectory)' - condition: and(succeededOrFailed(), eq(variables['system.pullrequest.isfork'], false)) - - - ${{ if eq(parameters.os, 'Linux') }}: - - task: CopyFiles@2 - displayName: Copy Deb Installer - inputs: - SourceFolder: '$(Build.Repository.LocalPath)/Package/Release/Packages' - Contents: '**/*.deb' - TargetFolder: '$(Build.ArtifactStagingDirectory)' - condition: and(succeededOrFailed(), eq(variables['system.pullrequest.isfork'], false)) - - - ${{ if eq(parameters.os, 'macOS') }}: - - task: CopyFiles@2 - displayName: Copy Pkg Installer - inputs: - SourceFolder: '$(Build.Repository.LocalPath)/Package/Release/Packages' - Contents: '**/*.pkg' - TargetFolder: '$(Build.ArtifactStagingDirectory)' - condition: and(succeededOrFailed(), eq(variables['system.pullrequest.isfork'], false)) - - - task: CopyFiles@2 - displayName: Copy Build Logs - inputs: - Contents: '*.binlog' - TargetFolder: '$(Build.ArtifactStagingDirectory)' - condition: and(succeededOrFailed(), eq(variables['system.pullrequest.isfork'], false)) - - - task: PublishBuildArtifacts@1 - displayName: Publish Artifacts - inputs: - ArtifactName: ${{ format('{0} Artifacts', parameters.os) }} - condition: and(succeededOrFailed(), eq(variables['system.pullrequest.isfork'], false)) diff --git a/src/core/IronPython.Modules/_ctypes/CData.cs b/src/core/IronPython.Modules/_ctypes/CData.cs index 61e63bdc5..e6974d9cb 100644 --- a/src/core/IronPython.Modules/_ctypes/CData.cs +++ b/src/core/IronPython.Modules/_ctypes/CData.cs @@ -72,8 +72,11 @@ internal void SetAddress(IntPtr address) { internal void InitializeFromBuffer(object? data, int offset, int size) { var bp = data as IBufferProtocol +#if PYTHON_34 ?? throw PythonOps.TypeErrorForBadInstance("{0} object does not have the buffer interface", data); - // Python 3.5: PythonOps.TypeErrorForBytesLikeTypeMismatch(data); +#else + ?? throw PythonOps.TypeErrorForBytesLikeTypeMismatch(data); +#endif IPythonBuffer buffer = bp.GetBuffer(BufferFlags.FullRO); if (buffer.IsReadOnly) { @@ -97,8 +100,11 @@ internal void InitializeFromBuffer(object? data, int offset, int size) { internal void InitializeFromBufferCopy(object? data, int offset, int size) { var bp = data as IBufferProtocol +#if PYTHON_34 ?? throw PythonOps.TypeErrorForBadInstance("{0} object does not have the buffer interface", data); - // Python 3.5: PythonOps.TypeErrorForBytesLikeTypeMismatch(data); +#else + ?? throw PythonOps.TypeErrorForBytesLikeTypeMismatch(data); +#endif using IPythonBuffer buffer = bp.GetBuffer(); var span = buffer.AsReadOnlySpan(); diff --git a/src/core/IronPython.Modules/_ctypes/SimpleType.cs b/src/core/IronPython.Modules/_ctypes/SimpleType.cs index 14475cc33..2bdcf6467 100644 --- a/src/core/IronPython.Modules/_ctypes/SimpleType.cs +++ b/src/core/IronPython.Modules/_ctypes/SimpleType.cs @@ -58,8 +58,18 @@ public SimpleType(CodeContext/*!*/ context, string name, PythonTuple bases, Pyth case 'H': _type = SimpleTypeKind.UnsignedShort; break; case 'i': _type = SimpleTypeKind.SignedInt; break; case 'I': _type = SimpleTypeKind.UnsignedInt; break; - case 'l': _type = SimpleTypeKind.SignedLong; break; - case 'L': _type = SimpleTypeKind.UnsignedLong; break; + case 'l': + _type = SimpleTypeKind.SignedLong; +#if PYTHON_36_OR_GREATER + _charType = TypecodeOps.IsCLong32Bit ? _charType : 'q'; +#endif + break; + case 'L': + _type = SimpleTypeKind.UnsignedLong; +#if PYTHON_36_OR_GREATER + _charType = TypecodeOps.IsCLong32Bit ? _charType : 'Q'; +#endif + break; case 'f': _type = SimpleTypeKind.Single; break; case 'g': // long double, new in 2.6 case 'd': _type = SimpleTypeKind.Double; break; diff --git a/src/core/IronPython.Modules/_datetime.cs b/src/core/IronPython.Modules/_datetime.cs index e05d2be26..5c217e1fd 100644 --- a/src/core/IronPython.Modules/_datetime.cs +++ b/src/core/IronPython.Modules/_datetime.cs @@ -54,13 +54,15 @@ internal timedelta(TimeSpan ts, double microsecond) } public timedelta(double days, double seconds, double microseconds, double milliseconds, double minutes, double hours, double weeks) { - double totalDays = weeks * 7 + days; - double totalSeconds = ((totalDays * 24 + hours) * 60 + minutes) * 60 + seconds; + double totalSeconds = (((weeks * 7 + days) * 24 + hours) * 60 + minutes) * 60 + seconds; + CheckDouble(totalSeconds); double totalSecondsSharp = Math.Floor(totalSeconds); double totalSecondsFloat = totalSeconds - totalSecondsSharp; double totalMicroseconds = Math.Round(totalSecondsFloat * 1e6 + milliseconds * 1000 + microseconds); + CheckDouble(totalMicroseconds); + double otherSecondsFromMicroseconds = Math.Floor(totalMicroseconds / 1e6); totalSecondsSharp += otherSecondsFromMicroseconds; @@ -71,28 +73,45 @@ public timedelta(double days, double seconds, double microseconds, double millis totalMicroseconds += 1e6; } - _days = (int)(totalSecondsSharp / SECONDSPERDAY); - _seconds = (int)(totalSecondsSharp - _days * SECONDSPERDAY); + _days = ToInt(totalSecondsSharp / SECONDSPERDAY); + _seconds = ToInt(totalSecondsSharp - _days * SECONDSPERDAY); if (_seconds < 0) { _days--; _seconds += (int)SECONDSPERDAY; } - _microseconds = (int)(totalMicroseconds); + _microseconds = ToInt(totalMicroseconds); if (Math.Abs(_days) > MAXDAYS) { throw PythonOps.OverflowError("days={0}; must have magnitude <= 999999999", _days); } + + static void CheckDouble(double d) { + if (double.IsInfinity(d)) { + throw PythonOps.OverflowError("cannot convert float infinity to integer"); + } else if (double.IsNaN(d)) { + throw PythonOps.ValueError("cannot convert float NaN to integer"); + } + } + + static int ToInt(double d) { + if (Int32.MinValue <= d && d <= Int32.MaxValue) { + return (int)d; + } else { + CheckDouble(d); + return checked((int)d); + } + } } public static timedelta __new__(CodeContext context, [NotNone] PythonType cls, - double days = 0D, - double seconds = 0D, - double microseconds = 0D, - double milliseconds = 0D, - double minutes = 0D, - double hours = 0D, - double weeks = 0D) { + double days = 0, + double seconds = 0, + double microseconds = 0, + double milliseconds = 0, + double minutes = 0, + double hours = 0, + double weeks = 0) { if (cls == DynamicHelpers.GetPythonTypeFromType(typeof(timedelta))) { return new timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks); } else { @@ -1218,7 +1237,7 @@ public PythonTuple __reduce__() { ); } - // TODO: get rid of __bool__ in 3.5 +#if PYTHON_34 // removed in 3.5 public bool __bool__() { return this.UtcTime.TimeSpan.Ticks != 0 || this.UtcTime.LostMicroseconds != 0; } @@ -1226,6 +1245,7 @@ public bool __bool__() { public static explicit operator bool([NotNone] time time) { return time.__bool__(); } +#endif // instance methods public object replace() { diff --git a/src/core/IronPython.Modules/_heapq.cs b/src/core/IronPython.Modules/_heapq.cs index 6db8b5810..55c2280e7 100644 --- a/src/core/IronPython.Modules/_heapq.cs +++ b/src/core/IronPython.Modules/_heapq.cs @@ -77,7 +77,7 @@ public static void heappush(CodeContext/*!*/ context, [NotNone] PythonList list, } } - // TODO: removed in Python 3.5 +#if PYTHON_34 // removed in 3.5 [Documentation("Find the n largest elements in a dataset.\n\n" + "Equivalent to: sorted(iterable, reverse=True)[:n]\n" )] @@ -110,7 +110,6 @@ public static PythonList nlargest(CodeContext/*!*/ context, int n, object? itera return ret; } - // TODO: removed in Python 3.5 [Documentation("Find the n smallest elements in a dataset.\n\n" + "Equivalent to: sorted(iterable)[:n]\n" )] @@ -142,6 +141,7 @@ public static PythonList nsmallest(CodeContext/*!*/ context, int n, object? iter HeapSort(context, ret); return ret; } +#endif #endregion diff --git a/src/core/IronPython.Modules/_sre.cs b/src/core/IronPython.Modules/_sre.cs index 26f88ff33..071d3f873 100644 --- a/src/core/IronPython.Modules/_sre.cs +++ b/src/core/IronPython.Modules/_sre.cs @@ -14,7 +14,11 @@ namespace IronPython.Modules { public static class PythonSRegEx { public const string __doc__ = "non-functional _sre module. Included only for completeness."; +#if PYTHON_34 public const int MAGIC = 20031017; +#else + public const int MAGIC = 20140917; +#endif public const int CODESIZE = 2; public const int MAXREPEAT = 65535; public const int MAXGROUPS = int.MaxValue; diff --git a/src/core/IronPython.Modules/_winapi.cs b/src/core/IronPython.Modules/_winapi.cs index d26d03ec6..6568c5467 100644 --- a/src/core/IronPython.Modules/_winapi.cs +++ b/src/core/IronPython.Modules/_winapi.cs @@ -15,6 +15,8 @@ using IronPython.Runtime; using IronPython.Runtime.Operations; +using Microsoft.Win32.SafeHandles; + [assembly: PythonModule("_winapi", typeof(IronPython.Modules.PythonWinApi), PlatformsAttribute.PlatformFamily.Windows)] namespace IronPython.Modules { [SupportedOSPlatform("windows")] @@ -234,6 +236,16 @@ public static int WaitForSingleObject(BigInteger handle, int dwMilliseconds) { return WaitForSingleObjectPI(new IntPtr((long)handle), dwMilliseconds); } + public static void SetNamedPipeHandleState(BigInteger named_pipe, object? mode, object? max_collection_count, object? collect_data_timeout) { + if (max_collection_count is not null) throw new NotImplementedException(); + if (collect_data_timeout is not null) throw new NotImplementedException(); + var pipeHandle = new SafePipeHandle(new IntPtr((long)named_pipe), false); + int m = Converter.ConvertToInt32(mode); + var result = Interop.Kernel32.SetNamedPipeHandleState(pipeHandle, ref m, IntPtr.Zero, IntPtr.Zero); + + if (!result) throw PythonNT.GetLastWin32Error(); + } + #endregion #region struct's and enum's diff --git a/src/core/IronPython.Modules/mmap.cs b/src/core/IronPython.Modules/mmap.cs index 94c31e3a5..a02f82ba2 100644 --- a/src/core/IronPython.Modules/mmap.cs +++ b/src/core/IronPython.Modules/mmap.cs @@ -338,6 +338,10 @@ public MmapDefault(CodeContext/*!*/ context, int fileno, long length, string? ta _offset = 0; // offset is ignored without an underlying file _sourceStream = null; + if (length == 0) { + throw PythonNT.GetOsError(PythonErrno.EINVAL); + } + // work around the .NET bug whereby CreateOrOpen throws on a null mapName if (_mapName is null) { _file = MemoryMappedFile.CreateNew(null, length, _fileAccess); @@ -859,7 +863,7 @@ public Bytes read(int len) { len = checked((int)(_view.Capacity - pos)); } - if (len == 0) { + if (len <= 0) { return Bytes.Empty; } @@ -960,11 +964,6 @@ public void resize(long newsize) { } } - if (_sourceStream == null) { - // resizing is not supported without an underlying file - throw WindowsError(PythonExceptions._OSError.ERROR_INVALID_PARAMETER); - } - if (_view.Capacity == newsize) { // resizing to the same size return; @@ -979,6 +978,33 @@ public void resize(long newsize) { ); } + if (_sourceStream is null) { + // resizing of anonymous map + // TODO: non-copying implementation? + + MemoryMappedFile file; + // work around the .NET bug whereby CreateOrOpen throws on a null mapName + if (_mapName is null) { + file = MemoryMappedFile.CreateNew(null, newsize, _fileAccess); + } else { + Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); + file = MemoryMappedFile.CreateOrOpen(_mapName, newsize, _fileAccess); + } + + using (var oldStream = _file.CreateViewStream(0, Math.Min(_view.Capacity, newsize))) { + using var newStream = file.CreateViewStream(); + oldStream.CopyTo(newStream); + } + + _view.Flush(); + _view.Dispose(); + _file.Dispose(); + + _file = file; + _view = _file.CreateViewAccessor(_offset, newsize, _fileAccess); + return; + } + _view.Flush(); _view.Dispose(); _file.Dispose(); diff --git a/src/core/IronPython.Modules/nt.cs b/src/core/IronPython.Modules/nt.cs index ea48bc5e1..7d6d9c20b 100644 --- a/src/core/IronPython.Modules/nt.cs +++ b/src/core/IronPython.Modules/nt.cs @@ -849,6 +849,8 @@ public static object open(CodeContext/*!*/ context, [NotNone] string path, int f } } + VerifyPath(path, functionName: nameof(open), argName: nameof(path)); + if ((RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) && !ClrModule.IsMono) { // Use PosixFileStream to operate on fd directly // On Mono, we must use FileStream due to limitations in MemoryMappedFile diff --git a/src/core/IronPython.Modules/re.cs b/src/core/IronPython.Modules/re.cs index 718dd709a..7708204cf 100644 --- a/src/core/IronPython.Modules/re.cs +++ b/src/core/IronPython.Modules/re.cs @@ -165,8 +165,9 @@ public class Pattern : IWeakReferenceable { internal Pattern(CodeContext/*!*/ context, object pattern, ReFlags flags = 0, bool compiled = false) { _prePattern = PreParseRegex(context, PatternAsString(pattern, ref flags), verbose: flags.HasFlag(ReFlags.VERBOSE), isBytes: !flags.HasFlag(ReFlags.UNICODE), out ReFlags options); flags |= options; - // TODO: re-enable in 3.6 - // if (flags.HasFlag(ReFlags.UNICODE | ReFlags.LOCALE)) throw PythonOps.ValueError("cannot use LOCALE flag with a str pattern"); +#if PYTHON_36_OR_GREATER + if (flags.HasFlag(ReFlags.UNICODE | ReFlags.LOCALE)) throw PythonOps.ValueError("cannot use LOCALE flag with a str pattern"); +#endif if (flags.HasFlag(ReFlags.ASCII | ReFlags.LOCALE)) throw PythonOps.ValueError("ASCII and LOCALE flags are incompatible"); _re = GenRegex(context, _prePattern, flags, compiled, false); this.pattern = pattern; @@ -418,7 +419,7 @@ public object sub(CodeContext/*!*/ context, object? repl, object? @string, int c // only when not adjacent to a previous match if (string.IsNullOrEmpty(match.Value) && match.Index == prevEnd) { return ""; - }; + } prevEnd = match.Index + match.Length; if (replacement != null) return UnescapeGroups(context, match, replacement); @@ -445,7 +446,7 @@ public PythonTuple subn(CodeContext/*!*/ context, object? repl, object? @string, // only when not adjacent to a previous match if (string.IsNullOrEmpty(match.Value) && match.Index == prevEnd) { return ""; - }; + } prevEnd = match.Index + match.Length; totalCount++; diff --git a/src/core/IronPython/Compiler/Ast/TupleExpression.cs b/src/core/IronPython/Compiler/Ast/TupleExpression.cs index eeda8c3da..cc80ecef3 100644 --- a/src/core/IronPython/Compiler/Ast/TupleExpression.cs +++ b/src/core/IronPython/Compiler/Ast/TupleExpression.cs @@ -17,17 +17,20 @@ public TupleExpression(bool expandable, params Expression[] items) } internal override string? CheckAssign() { +#if !PYTHON_36_OR_GREATER if (Items.Count == 0) { - // TODO: remove this when we get to 3.6 return "can't assign to ()"; } +#endif return base.CheckAssign(); } internal override string? CheckDelete() { +#if !PYTHON_36_OR_GREATER if (Items.Count == 0) - return "can't delete ()"; // TODO: remove this when we get to 3.6 + return "can't delete ()"; +#endif return base.CheckDelete(); } diff --git a/src/core/IronPython/Hosting/Python.cs b/src/core/IronPython/Hosting/Python.cs index 32e666307..e91f3d622 100644 --- a/src/core/IronPython/Hosting/Python.cs +++ b/src/core/IronPython/Hosting/Python.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Collections.Generic; @@ -198,11 +200,11 @@ public static class Python { /// /// /// - public static void ImportModule (this ScriptScope/*!*/ scope, string/*!*/ moduleName) { - ContractUtils.RequiresNotNull (scope, nameof(scope)); - ContractUtils.RequiresNotNull (moduleName, nameof(moduleName)); + public static void ImportModule(this ScriptScope/*!*/ scope, string/*!*/ moduleName) { + ContractUtils.RequiresNotNull(scope, nameof(scope)); + ContractUtils.RequiresNotNull(moduleName, nameof(moduleName)); - scope.SetVariable (moduleName, scope.Engine.ImportModule (moduleName)); + scope.SetVariable(moduleName, scope.Engine.ImportModule(moduleName)); } /// @@ -270,12 +272,12 @@ public static void CallTracing(this ScriptEngine/*!*/ engine, object traceFunc, /// /// The ScriptRuntimeSetup object can then be additional configured and used to create a ScriptRuntime. /// - public static ScriptRuntimeSetup/*!*/ CreateRuntimeSetup(IDictionary options) { + public static ScriptRuntimeSetup/*!*/ CreateRuntimeSetup(IDictionary? options) { ScriptRuntimeSetup setup = new ScriptRuntimeSetup(); setup.LanguageSetups.Add(CreateLanguageSetup(options)); if (options != null) { - object value; + object? value; if (options.TryGetValue("Debug", out value) && value is bool && (bool)value) { @@ -298,7 +300,7 @@ value is bool && /// The LanguageSetup object can be used with other LanguageSetup objects from other languages to /// configure a ScriptRuntimeSetup object. /// - public static LanguageSetup/*!*/ CreateLanguageSetup(IDictionary options) { + public static LanguageSetup/*!*/ CreateLanguageSetup(IDictionary? options) { var setup = new LanguageSetup( typeof(PythonContext).AssemblyQualifiedName, PythonContext.IronPythonDisplayName, @@ -360,7 +362,7 @@ public static string[] GetModuleFilenames(this ScriptEngine engine) { } private static PythonContext/*!*/ GetPythonContext(ScriptEngine/*!*/ engine) { - return HostingHelpers.GetLanguageContext(engine) as PythonContext; + return (PythonContext)HostingHelpers.GetLanguageContext(engine); } #endregion diff --git a/src/core/IronPython/Hosting/PythonCodeDomCodeGen.cs b/src/core/IronPython/Hosting/PythonCodeDomCodeGen.cs index 76c711b01..65455b9c6 100644 --- a/src/core/IronPython/Hosting/PythonCodeDomCodeGen.cs +++ b/src/core/IronPython/Hosting/PythonCodeDomCodeGen.cs @@ -2,8 +2,11 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System.CodeDom; using System.Collections.Generic; + using Microsoft.Scripting.Runtime; #if FEATURE_CODEDOM @@ -44,8 +47,7 @@ protected override void WriteSnippetStatement(CodeSnippetStatement s) { int indentLen = lastLine.Length; if (indentLen > _indents.Peek()) { _indents.Push(indentLen); - } - else { + } else { while (indentLen < _indents.Peek()) { _indents.Pop(); } @@ -94,4 +96,4 @@ private string IndentSnippetStatement(string block) { } } -#endif \ No newline at end of file +#endif diff --git a/src/core/IronPython/Hosting/PythonCommandLine.cs b/src/core/IronPython/Hosting/PythonCommandLine.cs index 2fc86f071..1c4b4c453 100644 --- a/src/core/IronPython/Hosting/PythonCommandLine.cs +++ b/src/core/IronPython/Hosting/PythonCommandLine.cs @@ -2,9 +2,11 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.IO.MemoryMappedFiles; using System.Reflection; @@ -35,7 +37,7 @@ public class PythonCommandLine : CommandLine { public PythonCommandLine() { } - protected override string Logo => PythonContext.PythonOptions.Quiet ? null : GetLogoDisplay(); + protected override string? Logo => PythonContext.PythonOptions.Quiet ? null : GetLogoDisplay(); /// /// Returns the display look for IronPython. @@ -49,7 +51,7 @@ public static string GetLogoDisplay() { } private int GetEffectiveExitCode(SystemExitException/*!*/ e) { - object nonIntegerCode; + object? nonIntegerCode; int exitCode = e.GetExitCode(out nonIntegerCode); if (nonIntegerCode != null) { Console.WriteLine(nonIntegerCode.ToString(), Style.Error); @@ -121,8 +123,8 @@ protected override int Run() { int result = base.Run(); // Check if IRONPYTHONINSPECT was set during execution - string inspectLine = Environment.GetEnvironmentVariable("IRONPYTHONINSPECT"); - if (inspectLine != null && !Options.Introspection) + string? inspectLine = Environment.GetEnvironmentVariable("IRONPYTHONINSPECT"); + if (!string.IsNullOrEmpty(inspectLine) && !Options.Introspection) result = RunInteractiveLoop(); return result; @@ -139,8 +141,6 @@ protected override int RunInteractiveLoop() { #region Initialization protected override void Initialize() { - Debug.Assert(Language != null); - base.Initialize(); Console.Output = new OutputWriter(PythonContext, false); @@ -168,8 +168,8 @@ protected override void Initialize() { // Equivalent to -i command line option // Check if IRONPYTHONINSPECT was set before execution - string inspectLine = Environment.GetEnvironmentVariable("IRONPYTHONINSPECT"); - if (inspectLine != null) + string? inspectLine = Environment.GetEnvironmentVariable("IRONPYTHONINSPECT"); + if (!string.IsNullOrEmpty(inspectLine)) Options.Introspection = true; // If running in console mode (including with -c), the current working directory should be @@ -198,7 +198,7 @@ protected override void Initialize() { fullPath = Path.GetDirectoryName( Language.DomainManager.Platform.GetFullPath(Options.FileName) - ); + )!; } } @@ -224,8 +224,8 @@ protected override void Initialize() { private void InitializePath(ref int pathIndex) { // paths, environment vars if (!Options.IgnoreEnvironmentVariables) { - string path = Environment.GetEnvironmentVariable("IRONPYTHONPATH"); - if (path != null && path.Length > 0) { + string? path = Environment.GetEnvironmentVariable("IRONPYTHONPATH"); + if (!string.IsNullOrEmpty(path)) { string[] paths = path.Split(Path.PathSeparator); foreach (string p in paths) { PythonContext.InsertIntoPath(pathIndex++, p); @@ -236,7 +236,7 @@ private void InitializePath(ref int pathIndex) { private void InitializeEnvironmentVariables() { if (!Options.IgnoreEnvironmentVariables) { - string warnings = Environment.GetEnvironmentVariable("IRONPYTHONWARNINGS"); + string? warnings = Environment.GetEnvironmentVariable("IRONPYTHONWARNINGS"); object o = PythonContext.GetSystemStateValue("warnoptions"); if (o == null) { o = new PythonList(); @@ -254,13 +254,13 @@ private void InitializeEnvironmentVariables() { private void InitializeModules() { string executable = ""; - string prefix = null; + string? prefix = null; - Assembly entryAssembly = Assembly.GetEntryAssembly(); + Assembly? entryAssembly = Assembly.GetEntryAssembly(); // Can be null if called from unmanaged code (VS integration scenario) if (entryAssembly != null) { executable = entryAssembly.Location; - prefix = Path.GetDirectoryName(executable); + prefix = Path.GetDirectoryName(executable)!; var name = Path.GetFileNameWithoutExtension(executable); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { @@ -285,7 +285,7 @@ private void InitializeModules() { } if (prefix is not null) { - string pyvenv_prefix = null; + string? pyvenv_prefix = null; // look for pyvenv.cfg in the current folder and then the parent folder var path = Path.Combine(prefix, "pyvenv.cfg"); @@ -302,7 +302,9 @@ private void InitializeModules() { } break; } - path = Path.Combine(Path.GetDirectoryName(prefix), "pyvenv.cfg"); + var parent = Path.GetDirectoryName(prefix); + if (parent is null) break; + path = Path.Combine(parent, "pyvenv.cfg"); } prefix = pyvenv_prefix ?? prefix; @@ -317,8 +319,8 @@ private void InitializeModules() { // --- Local functions ------- - static bool FindRunner(string prefix, string name, string assembly, out string runner) { - runner = null; + static bool FindRunner([DisallowNull] string? prefix, string name, string assembly, [NotNullWhen(true)] out string? runner) { + runner = string.Empty; #if NET while (prefix != null) { runner = Path.Combine(prefix, name); @@ -339,7 +341,7 @@ static bool FindRunner(string prefix, string name, string assembly, out string r using var mmf = MemoryMappedFile.CreateFromFile(runner, FileMode.Open, null, 0, MemoryMappedFileAccess.Read); using var accessor = mmf.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read); - for (long i = accessor.Capacity - fsAssemblyPath.Length; i >= 0; i--) { // the path should be close to the end of the file + for (long i = accessor.Capacity - fsAssemblyPath.Length; i >= 0; i--) { // the path should be close to the end of the file if (accessor.ReadByte(i) != fsap0) continue; bool found = true; @@ -354,6 +356,7 @@ static bool FindRunner(string prefix, string name, string assembly, out string r } catch { } // if reading the file fails, it is not our runner } #endif + runner = null; return false; } @@ -458,8 +461,8 @@ private void RunStartup() { if (Options.IgnoreEnvironmentVariables) return; - string startup = Environment.GetEnvironmentVariable("IRONPYTHONSTARTUP"); - if (startup != null && startup.Length > 0) { + string? startup = Environment.GetEnvironmentVariable("IRONPYTHONSTARTUP"); + if (!string.IsNullOrEmpty(startup)) { if (Options.HandleExceptions) { try { ExecuteCommand(Engine.CreateScriptSourceFromFile(startup)); diff --git a/src/core/IronPython/Hosting/PythonConsoleOptions.cs b/src/core/IronPython/Hosting/PythonConsoleOptions.cs index b8b3dde7e..f279bb376 100644 --- a/src/core/IronPython/Hosting/PythonConsoleOptions.cs +++ b/src/core/IronPython/Hosting/PythonConsoleOptions.cs @@ -2,7 +2,10 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; + using Microsoft.Scripting.Hosting.Shell; namespace IronPython.Hosting { @@ -12,7 +15,7 @@ public sealed class PythonConsoleOptions : ConsoleOptions { public bool SkipImportSite { get; set; } - public string ModuleToRun { get; set; } + public string? ModuleToRun { get; set; } /// /// Gets or sets a value indicating whether to skip the first line of the code to execute. diff --git a/src/core/IronPython/Hosting/PythonOptionsParser.cs b/src/core/IronPython/Hosting/PythonOptionsParser.cs index 1bd42ee80..277f0847a 100644 --- a/src/core/IronPython/Hosting/PythonOptionsParser.cs +++ b/src/core/IronPython/Hosting/PythonOptionsParser.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Collections.Generic; using System.Diagnostics; @@ -16,7 +18,7 @@ namespace IronPython.Hosting { public sealed class PythonOptionsParser : OptionsParser { - private List _warningFilters; + private List? _warningFilters; public PythonOptionsParser() { } @@ -205,8 +207,8 @@ protected override void ParseArgument(string/*!*/ arg) { } } - protected override void HandleImplementationSpecificOption(string arg, string val) { - object frames; + protected override void HandleImplementationSpecificOption(string arg, string? val) { + object? frames; switch (arg) { case "NoFrames": if (LanguageSetup.Options.TryGetValue("Frames", out frames) && frames != ScriptingRuntimeHelpers.False) { diff --git a/src/core/IronPython/Hosting/PythonService.cs b/src/core/IronPython/Hosting/PythonService.cs index c790b9b8e..4a0d39ccc 100644 --- a/src/core/IronPython/Hosting/PythonService.cs +++ b/src/core/IronPython/Hosting/PythonService.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + #if FEATURE_REMOTING using System.Runtime.Remoting; #else @@ -11,8 +13,10 @@ using System; using System.Collections.Generic; using System.Threading; + using IronPython.Runtime; using IronPython.Runtime.Operations; + using Microsoft.Scripting.Hosting; using Microsoft.Scripting.Hosting.Providers; using Microsoft.Scripting.Utils; @@ -27,7 +31,7 @@ namespace IronPython.Hosting { public sealed class PythonService : MarshalByRefObject { private readonly ScriptEngine/*!*/ _engine; private readonly PythonContext/*!*/ _context; - private ScriptScope _sys, _builtins, _clr; + private ScriptScope? _sys, _builtins, _clr; public PythonService(PythonContext/*!*/ context, ScriptEngine/*!*/ engine) { Assert.NotNull(context, engine); @@ -76,7 +80,7 @@ public PythonService(PythonContext/*!*/ context, ScriptEngine/*!*/ engine) { _context.PublishModule(name, module); module.__init__(name, docString); module.__dict__["__file__"] = filename; - + return HostingHelpers.CreateScriptScope(_engine, module.Scope); } @@ -109,7 +113,7 @@ public void DispatchCommand(Action command) { } #if FEATURE_REMOTING - public ObjectHandle GetSetCommandDispatcher(ObjectHandle dispatcher) { + public ObjectHandle? GetSetCommandDispatcher(ObjectHandle dispatcher) { var res = _context.GetSetCommandDispatcher((Action)dispatcher.Unwrap()); if (res != null) { return new ObjectHandle(res); diff --git a/src/core/IronPython/Interop/Windows/Kernel32/Interop.SetNamedPipeHandleState.cs b/src/core/IronPython/Interop/Windows/Kernel32/Interop.SetNamedPipeHandleState.cs new file mode 100644 index 000000000..fb6d24b1d --- /dev/null +++ b/src/core/IronPython/Interop/Windows/Kernel32/Interop.SetNamedPipeHandleState.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.Win32.SafeHandles; + +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop { + internal static partial class Kernel32 { + [DllImport(Libraries.Kernel32, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern unsafe bool SetNamedPipeHandleState( + SafePipeHandle hNamedPipe, + ref int lpMode, + IntPtr lpMaxCollectionCount, + IntPtr lpCollectDataTimeout + ); + } +} diff --git a/src/core/IronPython/Modules/Builtin.cs b/src/core/IronPython/Modules/Builtin.cs index db1000ea0..b16807d79 100644 --- a/src/core/IronPython/Modules/Builtin.cs +++ b/src/core/IronPython/Modules/Builtin.cs @@ -58,7 +58,11 @@ public static object __import__(CodeContext/*!*/ context, [NotNone] string name, object ret = Importer.ImportModule(context, globals, name, from != null && from.Count > 0, level); if (ret == null) { +#if PYTHON_36_OR_GREATER // ModuleNotFoundError since Python 3.6 + var err = PythonOps.ModuleNotFoundError("No module named {0}", PythonOps.Repr(context, name)); +#else var err = PythonOps.ImportError("No module named '{0}'", name); +#endif ((PythonExceptions._ImportError)err.GetPythonException()!).name = name; return LightExceptions.Throw(err); } diff --git a/src/core/IronPython/Runtime/Binding/BindingWarnings.cs b/src/core/IronPython/Runtime/Binding/BindingWarnings.cs index 9776e3297..ec50e9a4c 100644 --- a/src/core/IronPython/Runtime/Binding/BindingWarnings.cs +++ b/src/core/IronPython/Runtime/Binding/BindingWarnings.cs @@ -2,9 +2,11 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; +using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; -using System.Reflection; using System.Threading; using IronPython.Runtime.Exceptions; @@ -20,7 +22,7 @@ namespace IronPython.Runtime.Binding { /// Provides support for emitting warnings when built in methods are invoked at runtime. /// internal static class BindingWarnings { - public static bool ShouldWarn(PythonContext/*!*/ context, OverloadInfo/*!*/ method, out WarningInfo info) { + public static bool ShouldWarn(PythonContext/*!*/ context, OverloadInfo/*!*/ method, [NotNullWhen(true)] out WarningInfo? info) { Assert.NotNull(method); ObsoleteAttribute[] os = (ObsoleteAttribute[])method.ReflectionInfo.GetCustomAttributes(typeof(ObsoleteAttribute), true); @@ -39,25 +41,23 @@ public static bool ShouldWarn(PythonContext/*!*/ context, OverloadInfo/*!*/ meth #if FEATURE_APARTMENTSTATE // no apartment states on Silverlight - if (method.DeclaringType == typeof(Thread)) { - if (method.Name == "Sleep") { - info = new WarningInfo( - PythonExceptions.RuntimeWarning, - "Calling Thread.Sleep on an STA thread doesn't pump messages. Use Thread.CurrentThread.Join instead.", - Expression.Equal( - Expression.Call( - Expression.Property( - null, - typeof(Thread).GetProperty("CurrentThread") - ), - typeof(Thread).GetMethod("GetApartmentState") + if (method.DeclaringType == typeof(Thread) && method.Name == nameof(Thread.Sleep)) { + info = new WarningInfo( + PythonExceptions.RuntimeWarning, + "Calling Thread.Sleep on an STA thread doesn't pump messages. Use Thread.CurrentThread.Join instead.", + Expression.Equal( + Expression.Call( + Expression.Property( + null, + typeof(Thread).GetProperty(nameof(Thread.CurrentThread))! ), - AstUtils.Constant(ApartmentState.STA) - ) - ); + typeof(Thread).GetMethod(nameof(Thread.GetApartmentState))! + ), + AstUtils.Constant(ApartmentState.STA) + ) + ); - return true; - } + return true; } #endif diff --git a/src/core/IronPython/Runtime/Binding/CompatibilityInvokeBinder.cs b/src/core/IronPython/Runtime/Binding/CompatibilityInvokeBinder.cs index 1760542dc..397c335aa 100644 --- a/src/core/IronPython/Runtime/Binding/CompatibilityInvokeBinder.cs +++ b/src/core/IronPython/Runtime/Binding/CompatibilityInvokeBinder.cs @@ -2,19 +2,11 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable -using System; -using System.Collections.Generic; -using System.Diagnostics; using System.Dynamic; -using Microsoft.Scripting; using Microsoft.Scripting.Actions; -using Microsoft.Scripting.Actions.Calls; -using Microsoft.Scripting.Utils; - -using IronPython.Runtime.Operations; using AstUtils = Microsoft.Scripting.Ast.Utils; @@ -32,7 +24,7 @@ public CompatibilityInvokeBinder(PythonContext/*!*/ context, CallInfo /*!*/ call _context = context; } - public override DynamicMetaObject/*!*/ FallbackInvoke(DynamicMetaObject target, DynamicMetaObject/*!*/[]/*!*/ args, DynamicMetaObject errorSuggestion) { + public override DynamicMetaObject/*!*/ FallbackInvoke(DynamicMetaObject target, DynamicMetaObject/*!*/[]/*!*/ args, DynamicMetaObject? errorSuggestion) { if (target.Value is IDynamicMetaObjectProvider && errorSuggestion == null) { // try creating an instance... return target.BindCreateInstance( @@ -51,7 +43,7 @@ public CompatibilityInvokeBinder(PythonContext/*!*/ context, CallInfo /*!*/ call return InvokeFallback(target, args, BindingHelpers.CallInfoToSignature(CallInfo), errorSuggestion); } - internal DynamicMetaObject/*!*/ InvokeFallback(DynamicMetaObject/*!*/ target, DynamicMetaObject/*!*/[]/*!*/ args, CallSignature sig, DynamicMetaObject errorSuggestion) { + internal DynamicMetaObject/*!*/ InvokeFallback(DynamicMetaObject/*!*/ target, DynamicMetaObject/*!*/[]/*!*/ args, CallSignature sig, DynamicMetaObject? errorSuggestion) { return PythonProtocol.Call(this, target, args) ?? Context.Binder.Create(sig, target, args, AstUtils.Constant(_context.SharedContext)) ?? @@ -62,7 +54,7 @@ public override int GetHashCode() { return base.GetHashCode() ^ _context.Binder.GetHashCode(); } - public override bool Equals(object obj) { + public override bool Equals(object? obj) { if (!(obj is CompatibilityInvokeBinder ob)) { return false; } diff --git a/src/core/IronPython/Runtime/Binding/ContextArgBuilder.cs b/src/core/IronPython/Runtime/Binding/ContextArgBuilder.cs index 33edf183f..05e4ace62 100644 --- a/src/core/IronPython/Runtime/Binding/ContextArgBuilder.cs +++ b/src/core/IronPython/Runtime/Binding/ContextArgBuilder.cs @@ -2,15 +2,12 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable -using System.Collections.Generic; -using System.Diagnostics; +using System.Linq.Expressions; using System.Reflection; -using System; -using System.Dynamic; + using Microsoft.Scripting.Actions.Calls; -using Microsoft.Scripting.Utils; namespace IronPython.Runtime.Binding { diff --git a/src/core/IronPython/Runtime/Binding/CreateFallbackBinder.cs b/src/core/IronPython/Runtime/Binding/CreateFallbackBinder.cs index 2b6a9aaa0..5c4c51a5b 100644 --- a/src/core/IronPython/Runtime/Binding/CreateFallbackBinder.cs +++ b/src/core/IronPython/Runtime/Binding/CreateFallbackBinder.cs @@ -2,17 +2,9 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable -using System; -using System.Collections.Generic; -using System.Diagnostics; using System.Dynamic; -using IronPython.Runtime.Operations; -using Microsoft.Scripting; -using Microsoft.Scripting.Actions; -using Microsoft.Scripting.Utils; -using AstUtils = Microsoft.Scripting.Ast.Utils; namespace IronPython.Runtime.Binding { /// @@ -27,7 +19,7 @@ public CreateFallback(CompatibilityInvokeBinder/*!*/ realFallback, CallInfo /*!* _fallback = realFallback; } - public override DynamicMetaObject/*!*/ FallbackCreateInstance(DynamicMetaObject/*!*/ target, DynamicMetaObject/*!*/[]/*!*/ args, DynamicMetaObject errorSuggestion) { + public override DynamicMetaObject/*!*/ FallbackCreateInstance(DynamicMetaObject/*!*/ target, DynamicMetaObject/*!*/[]/*!*/ args, DynamicMetaObject? errorSuggestion) { return _fallback.InvokeFallback(target, args, BindingHelpers.GetCallSignature(this), errorSuggestion); } diff --git a/src/core/IronPython/Runtime/Binding/FastBindResult.cs b/src/core/IronPython/Runtime/Binding/FastBindResult.cs index e6866a55c..78c5d675d 100644 --- a/src/core/IronPython/Runtime/Binding/FastBindResult.cs +++ b/src/core/IronPython/Runtime/Binding/FastBindResult.cs @@ -2,17 +2,9 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; - -using System; -using System.Dynamic; -using System.Runtime.CompilerServices; - -using Microsoft.Scripting.Actions; +#nullable enable namespace IronPython.Runtime.Binding { - using Ast = Expression; - internal readonly struct FastBindResult where T : class { public readonly T Target; public readonly bool ShouldCache; diff --git a/src/core/IronPython/Runtime/Binding/FastGetBase.cs b/src/core/IronPython/Runtime/Binding/FastGetBase.cs index bb849308c..08dc878a3 100644 --- a/src/core/IronPython/Runtime/Binding/FastGetBase.cs +++ b/src/core/IronPython/Runtime/Binding/FastGetBase.cs @@ -39,4 +39,4 @@ protected static object Update(CallSite site, object self, CodeContext context) return ((CallSite>)site).Update(site, self, context); } } -} \ No newline at end of file +} diff --git a/src/core/IronPython/Runtime/Binding/IComConvertible.cs b/src/core/IronPython/Runtime/Binding/IComConvertible.cs index 4fdb80c4a..fa8690e17 100644 --- a/src/core/IronPython/Runtime/Binding/IComConvertible.cs +++ b/src/core/IronPython/Runtime/Binding/IComConvertible.cs @@ -2,10 +2,9 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Generic; +#nullable enable + using System.Dynamic; -using System.Text; namespace IronPython.Runtime.Binding { /// diff --git a/src/core/IronPython/Runtime/Binding/IFastGettable.cs b/src/core/IronPython/Runtime/Binding/IFastGettable.cs index fc728450c..5b438c75d 100644 --- a/src/core/IronPython/Runtime/Binding/IFastGettable.cs +++ b/src/core/IronPython/Runtime/Binding/IFastGettable.cs @@ -2,12 +2,7 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; - -using System; -using System.Dynamic; - -using Microsoft.Scripting.Actions; +#nullable enable using System.Runtime.CompilerServices; diff --git a/src/core/IronPython/Runtime/Binding/IFastInvokable.cs b/src/core/IronPython/Runtime/Binding/IFastInvokable.cs index e0bf05d73..48863a7bb 100644 --- a/src/core/IronPython/Runtime/Binding/IFastInvokable.cs +++ b/src/core/IronPython/Runtime/Binding/IFastInvokable.cs @@ -2,12 +2,9 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable -using System; -using System.Dynamic; using System.Runtime.CompilerServices; -using Microsoft.Scripting.Actions; namespace IronPython.Runtime.Binding { internal interface IFastInvokable { diff --git a/src/core/IronPython/Runtime/Binding/IFastSettable.cs b/src/core/IronPython/Runtime/Binding/IFastSettable.cs index dcfe19c99..570141fdf 100644 --- a/src/core/IronPython/Runtime/Binding/IFastSettable.cs +++ b/src/core/IronPython/Runtime/Binding/IFastSettable.cs @@ -2,14 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable -using System; -using System.Dynamic; - -using Microsoft.Scripting.Actions; - -using Microsoft.Scripting.Runtime; using System.Runtime.CompilerServices; namespace IronPython.Runtime.Binding { diff --git a/src/core/IronPython/Runtime/Binding/IPythonConvertible.cs b/src/core/IronPython/Runtime/Binding/IPythonConvertible.cs index ceb0e3edc..d4ed534ab 100644 --- a/src/core/IronPython/Runtime/Binding/IPythonConvertible.cs +++ b/src/core/IronPython/Runtime/Binding/IPythonConvertible.cs @@ -2,11 +2,9 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable -using System; using System.Dynamic; -using Microsoft.Scripting.Actions; namespace IronPython.Runtime.Binding { internal interface IPythonConvertible { diff --git a/src/core/IronPython/Runtime/Binding/IPythonGetable.cs b/src/core/IronPython/Runtime/Binding/IPythonGetable.cs index 468dbc2fe..77216976d 100644 --- a/src/core/IronPython/Runtime/Binding/IPythonGetable.cs +++ b/src/core/IronPython/Runtime/Binding/IPythonGetable.cs @@ -2,9 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable -using System; using System.Dynamic; namespace IronPython.Runtime.Binding { diff --git a/src/core/IronPython/Runtime/Binding/IPythonInvokable.cs b/src/core/IronPython/Runtime/Binding/IPythonInvokable.cs index 217e75fe9..008a3a42a 100644 --- a/src/core/IronPython/Runtime/Binding/IPythonInvokable.cs +++ b/src/core/IronPython/Runtime/Binding/IPythonInvokable.cs @@ -2,10 +2,10 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable -using System; using System.Dynamic; +using System.Linq.Expressions; namespace IronPython.Runtime.Binding { /// diff --git a/src/core/IronPython/Runtime/Binding/IPythonOperable.cs b/src/core/IronPython/Runtime/Binding/IPythonOperable.cs index e17eebd91..3927914ca 100644 --- a/src/core/IronPython/Runtime/Binding/IPythonOperable.cs +++ b/src/core/IronPython/Runtime/Binding/IPythonOperable.cs @@ -2,9 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Generic; -using System.Text; +#nullable enable + using System.Dynamic; namespace IronPython.Runtime.Binding { diff --git a/src/core/IronPython/Runtime/Binding/IPythonSite.cs b/src/core/IronPython/Runtime/Binding/IPythonSite.cs index d1aa81cd0..ad8879e93 100644 --- a/src/core/IronPython/Runtime/Binding/IPythonSite.cs +++ b/src/core/IronPython/Runtime/Binding/IPythonSite.cs @@ -1,6 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Text; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +#nullable enable namespace IronPython.Runtime.Binding { internal interface IPythonSite { diff --git a/src/core/IronPython/Runtime/Binding/MetaPythonObject.cs b/src/core/IronPython/Runtime/Binding/MetaPythonObject.cs index 3b0631a5c..f150ac9b4 100644 --- a/src/core/IronPython/Runtime/Binding/MetaPythonObject.cs +++ b/src/core/IronPython/Runtime/Binding/MetaPythonObject.cs @@ -2,16 +2,17 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable using System; -using System.Diagnostics; using System.Dynamic; -using Microsoft.Scripting.Actions; +using System.Linq.Expressions; + +using IronPython.Runtime.Operations; +using IronPython.Runtime.Types; + using Microsoft.Scripting.Ast; using Microsoft.Scripting.Runtime; -using IronPython.Runtime.Types; -using IronPython.Runtime.Operations; namespace IronPython.Runtime.Binding { using Ast = Expression; @@ -37,7 +38,7 @@ public MetaPythonObject(Expression/*!*/ expression, BindingRestrictions/*!*/ res internal static MethodCallExpression MakeTryGetTypeMember(PythonContext/*!*/ PythonContext, PythonTypeSlot dts, Expression self, ParameterExpression tmp) { return MakeTryGetTypeMember( PythonContext, - dts, + dts, tmp, self, Ast.Property( @@ -96,15 +97,13 @@ public PythonType/*!*/ PythonType { /// TODO: This should be specialized for each callable object /// protected static DynamicMetaObject/*!*/ MakeDelegateTarget(DynamicMetaObjectBinder/*!*/ action, Type/*!*/ toType, DynamicMetaObject/*!*/ arg) { - Debug.Assert(arg != null); - PythonContext state = PythonContext.GetPythonContext(action); CodeContext context = state != null ? state.SharedContext : DefaultContext.Default; - + return new DynamicMetaObject( Ast.Convert( Ast.Call( - typeof(PythonOps).GetMethod(nameof(PythonOps.GetDelegate)), + typeof(PythonOps).GetMethod(nameof(PythonOps.GetDelegate))!, AstUtils.Constant(context), arg.Expression, AstUtils.Constant(toType) @@ -138,6 +137,5 @@ protected static string GetGetMemberName(DynamicMetaObjectBinder member) { return gma.Name; } - } } diff --git a/src/core/IronPython/Runtime/Binding/PythonDeleteIndexBinder.cs b/src/core/IronPython/Runtime/Binding/PythonDeleteIndexBinder.cs index 9b05ba4fe..f07969ae1 100644 --- a/src/core/IronPython/Runtime/Binding/PythonDeleteIndexBinder.cs +++ b/src/core/IronPython/Runtime/Binding/PythonDeleteIndexBinder.cs @@ -2,16 +2,17 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable -using System; using System.Dynamic; +using System.Linq.Expressions; + +using IronPython.Runtime.Operations; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; -using AstUtils = Microsoft.Scripting.Ast.Utils; -using IronPython.Runtime.Operations; +using AstUtils = Microsoft.Scripting.Ast.Utils; namespace IronPython.Runtime.Binding { using Ast = Expression; @@ -24,15 +25,15 @@ public PythonDeleteIndexBinder(PythonContext/*!*/ context, int argCount) _context = context; } - public override DynamicMetaObject FallbackDeleteIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject errorSuggestion) { - return PythonProtocol.Index(this, PythonIndexType.DeleteItem, ArrayUtils.Insert(target, indexes),errorSuggestion); + public override DynamicMetaObject FallbackDeleteIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject? errorSuggestion) { + return PythonProtocol.Index(this, PythonIndexType.DeleteItem, ArrayUtils.Insert(target, indexes), errorSuggestion); } public override int GetHashCode() { return base.GetHashCode() ^ _context.Binder.GetHashCode(); } - public override bool Equals(object obj) { + public override bool Equals(object? obj) { if (!(obj is PythonDeleteIndexBinder ob)) { return false; } @@ -52,7 +53,7 @@ public PythonContext/*!*/ Context { public Expression/*!*/ CreateExpression() { return Ast.Call( - typeof(PythonOps).GetMethod(nameof(PythonOps.MakeDeleteIndexAction)), + typeof(PythonOps).GetMethod(nameof(PythonOps.MakeDeleteIndexAction))!, BindingHelpers.CreateBinderStateExpression(), AstUtils.Constant(CallInfo.ArgumentCount) ); diff --git a/src/core/IronPython/Runtime/Binding/PythonDeleteMemberBinder.cs b/src/core/IronPython/Runtime/Binding/PythonDeleteMemberBinder.cs index 5c3ee8175..6337961c9 100644 --- a/src/core/IronPython/Runtime/Binding/PythonDeleteMemberBinder.cs +++ b/src/core/IronPython/Runtime/Binding/PythonDeleteMemberBinder.cs @@ -2,16 +2,14 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable -using System; -using Microsoft.Scripting; using System.Dynamic; -using Microsoft.Scripting.Runtime; +using System.Linq.Expressions; -using IronPython.Runtime.Binding; using IronPython.Runtime.Operations; -using IronPython.Runtime.Types; + +using Microsoft.Scripting.Runtime; namespace IronPython.Runtime.Binding { using Ast = Expression; @@ -30,7 +28,7 @@ public PythonDeleteMemberBinder(PythonContext/*!*/ context, string/*!*/ name, bo _context = context; } - public override DynamicMetaObject FallbackDeleteMember(DynamicMetaObject self, DynamicMetaObject errorSuggestion) { + public override DynamicMetaObject FallbackDeleteMember(DynamicMetaObject self, DynamicMetaObject? errorSuggestion) { if (self.NeedsDeferral()) { return Defer(self); } @@ -48,7 +46,7 @@ public override int GetHashCode() { return base.GetHashCode() ^ _context.Binder.GetHashCode(); } - public override bool Equals(object obj) { + public override bool Equals(object? obj) { if (!(obj is PythonDeleteMemberBinder ob)) { return false; } @@ -64,7 +62,7 @@ public override string ToString() { public Expression CreateExpression() { return Ast.Call( - typeof(PythonOps).GetMethod(nameof(PythonOps.MakeDeleteAction)), + typeof(PythonOps).GetMethod(nameof(PythonOps.MakeDeleteAction))!, BindingHelpers.CreateBinderStateExpression(), AstUtils.Constant(Name) ); diff --git a/src/core/IronPython/Runtime/Binding/PythonDeleteSliceBinder.cs b/src/core/IronPython/Runtime/Binding/PythonDeleteSliceBinder.cs index af5c43ba1..e77e54e30 100644 --- a/src/core/IronPython/Runtime/Binding/PythonDeleteSliceBinder.cs +++ b/src/core/IronPython/Runtime/Binding/PythonDeleteSliceBinder.cs @@ -2,16 +2,16 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable -using System; using System.Dynamic; +using System.Linq.Expressions; + +using IronPython.Runtime.Operations; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; -using IronPython.Runtime.Operations; - namespace IronPython.Runtime.Binding { using Ast = Expression; @@ -30,7 +30,7 @@ public override int GetHashCode() { return base.GetHashCode() ^ _context.Binder.GetHashCode(); } - public override bool Equals(object obj) { + public override bool Equals(object? obj) { if (!(obj is PythonDeleteSliceBinder ob)) { return false; } @@ -50,7 +50,7 @@ public PythonContext/*!*/ Context { public Expression/*!*/ CreateExpression() { return Ast.Call( - typeof(PythonOps).GetMethod(nameof(PythonOps.MakeDeleteSliceBinder)), + typeof(PythonOps).GetMethod(nameof(PythonOps.MakeDeleteSliceBinder))!, BindingHelpers.CreateBinderStateExpression() ); } diff --git a/src/core/IronPython/Runtime/Binding/PythonGetSliceBinder.cs b/src/core/IronPython/Runtime/Binding/PythonGetSliceBinder.cs index 3cd18aaea..cf0cb1fb8 100644 --- a/src/core/IronPython/Runtime/Binding/PythonGetSliceBinder.cs +++ b/src/core/IronPython/Runtime/Binding/PythonGetSliceBinder.cs @@ -2,16 +2,16 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable -using System; using System.Dynamic; +using System.Linq.Expressions; + +using IronPython.Runtime.Operations; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; -using IronPython.Runtime.Operations; - namespace IronPython.Runtime.Binding { using Ast = Expression; @@ -30,7 +30,7 @@ public override int GetHashCode() { return base.GetHashCode() ^ _context.Binder.GetHashCode(); } - public override bool Equals(object obj) { + public override bool Equals(object? obj) { if (!(obj is PythonGetSliceBinder ob)) { return false; } @@ -50,7 +50,7 @@ public PythonContext/*!*/ Context { public Expression/*!*/ CreateExpression() { return Ast.Call( - typeof(PythonOps).GetMethod(nameof(PythonOps.MakeGetSliceBinder)), + typeof(PythonOps).GetMethod(nameof(PythonOps.MakeGetSliceBinder))!, BindingHelpers.CreateBinderStateExpression() ); } diff --git a/src/core/IronPython/Runtime/Binding/PythonIndexType.cs b/src/core/IronPython/Runtime/Binding/PythonIndexType.cs index bafaafefb..5ec89309c 100644 --- a/src/core/IronPython/Runtime/Binding/PythonIndexType.cs +++ b/src/core/IronPython/Runtime/Binding/PythonIndexType.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Generic; -using System.Text; +#nullable enable namespace IronPython.Runtime.Binding { internal enum PythonIndexType { @@ -15,5 +13,4 @@ internal enum PythonIndexType { SetSlice, DeleteSlice } - } diff --git a/src/core/IronPython/Runtime/Binding/PythonOperationKind.cs b/src/core/IronPython/Runtime/Binding/PythonOperationKind.cs index a2f0112a8..3f540daed 100644 --- a/src/core/IronPython/Runtime/Binding/PythonOperationKind.cs +++ b/src/core/IronPython/Runtime/Binding/PythonOperationKind.cs @@ -1,6 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Text; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +#nullable enable namespace IronPython.Runtime.Binding { /// diff --git a/src/core/IronPython/Runtime/Binding/PythonSetSliceBinder.cs b/src/core/IronPython/Runtime/Binding/PythonSetSliceBinder.cs index db3f13b12..260f9e038 100644 --- a/src/core/IronPython/Runtime/Binding/PythonSetSliceBinder.cs +++ b/src/core/IronPython/Runtime/Binding/PythonSetSliceBinder.cs @@ -2,16 +2,15 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable -using System; using System.Dynamic; - -using Microsoft.Scripting.Runtime; -using Microsoft.Scripting.Utils; +using System.Linq.Expressions; using IronPython.Runtime.Operations; +using Microsoft.Scripting.Runtime; +using Microsoft.Scripting.Utils; namespace IronPython.Runtime.Binding { using Ast = Expression; @@ -31,7 +30,7 @@ public override int GetHashCode() { return base.GetHashCode() ^ _context.Binder.GetHashCode(); } - public override bool Equals(object obj) { + public override bool Equals(object? obj) { if (!(obj is PythonSetSliceBinder ob)) { return false; } @@ -51,7 +50,7 @@ public PythonContext/*!*/ Context { public Expression/*!*/ CreateExpression() { return Ast.Call( - typeof(PythonOps).GetMethod(nameof(PythonOps.MakeSetSliceBinder)), + typeof(PythonOps).GetMethod(nameof(PythonOps.MakeSetSliceBinder))!, BindingHelpers.CreateBinderStateExpression() ); } diff --git a/src/core/IronPython/Runtime/Binding/SiteLocalStorageBuilder.cs b/src/core/IronPython/Runtime/Binding/SiteLocalStorageBuilder.cs index 949a9873d..4d8e44195 100644 --- a/src/core/IronPython/Runtime/Binding/SiteLocalStorageBuilder.cs +++ b/src/core/IronPython/Runtime/Binding/SiteLocalStorageBuilder.cs @@ -2,19 +2,19 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Linq.Expressions; +#nullable enable using System; -using System.Collections.Generic; -using System.Dynamic; +using System.Linq.Expressions; using System.Reflection; -using AstUtils = Microsoft.Scripting.Ast.Utils; + using Microsoft.Scripting.Actions.Calls; -using Microsoft.Scripting.Utils; + +using AstUtils = Microsoft.Scripting.Ast.Utils; namespace IronPython.Runtime.Binding { public sealed class SiteLocalStorageBuilder : ArgBuilder { - public SiteLocalStorageBuilder(ParameterInfo info) + public SiteLocalStorageBuilder(ParameterInfo info) : base(info) { } diff --git a/src/core/IronPython/Runtime/Binding/WarningInfo.cs b/src/core/IronPython/Runtime/Binding/WarningInfo.cs index b00e665c4..ff34f839a 100644 --- a/src/core/IronPython/Runtime/Binding/WarningInfo.cs +++ b/src/core/IronPython/Runtime/Binding/WarningInfo.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Dynamic; using System.Linq.Expressions; @@ -15,9 +17,9 @@ namespace IronPython.Runtime.Binding { internal class WarningInfo { private readonly string/*!*/ _message; private readonly PythonType/*!*/ _type; - private readonly Expression _condition; + private readonly Expression? _condition; - public WarningInfo(PythonType/*!*/ type, string/*!*/ message, Expression condition = null) { + public WarningInfo(PythonType/*!*/ type, string/*!*/ message, Expression? condition = null) { _message = message; _type = type; _condition = condition; @@ -25,7 +27,7 @@ public WarningInfo(PythonType/*!*/ type, string/*!*/ message, Expression conditi public DynamicMetaObject/*!*/ AddWarning(Expression/*!*/ codeContext, DynamicMetaObject/*!*/ result) { Expression warn = Expression.Call( - typeof(PythonOps).GetMethod(nameof(PythonOps.Warn)), + typeof(PythonOps).GetMethod(nameof(PythonOps.Warn))!, codeContext, AstUtils.Constant(_type), AstUtils.Constant(_message), diff --git a/src/core/IronPython/Runtime/CompareUtil.cs b/src/core/IronPython/Runtime/CompareUtil.cs index 5ecb25049..37d9fb2f8 100644 --- a/src/core/IronPython/Runtime/CompareUtil.cs +++ b/src/core/IronPython/Runtime/CompareUtil.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Collections.Generic; using System.Diagnostics; @@ -11,7 +13,7 @@ namespace IronPython.Runtime { internal class CompareUtil { [ThreadStatic] - private static Stack CmpStack; + private static Stack? CmpStack; internal static bool Check(object o) => CmpStack?.Contains(o) ?? false; @@ -27,13 +29,13 @@ internal static void Push(object o) { internal static void Pop(object o) { Debug.Assert(CmpStack != null && CmpStack.Count > 0); - Debug.Assert(CmpStack.Peek() == o); + Debug.Assert(CmpStack!.Peek() == o); CmpStack.Pop(); } internal static void Pop(object o1, object o2) { Debug.Assert(CmpStack != null && CmpStack.Count > 0); - Debug.Assert(CmpStack.Peek() is TwoObjects t && t.Equals(new TwoObjects(o1, o2))); + Debug.Assert(CmpStack!.Peek() is TwoObjects t && t.Equals(new TwoObjects(o1, o2))); CmpStack.Pop(); } @@ -55,7 +57,7 @@ public TwoObjects(object obj1, object obj2) { } public override int GetHashCode() => throw new NotSupportedException(); - public override bool Equals(object other) => other is TwoObjects o && o.obj1 == obj1 && o.obj2 == obj2; + public override bool Equals(object? other) => other is TwoObjects o && o.obj1 == obj1 && o.obj2 == obj2; } } } diff --git a/src/core/IronPython/Runtime/CompileFlags.cs b/src/core/IronPython/Runtime/CompileFlags.cs index b50bc0d75..4fb8a748f 100644 --- a/src/core/IronPython/Runtime/CompileFlags.cs +++ b/src/core/IronPython/Runtime/CompileFlags.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Runtime { diff --git a/src/core/IronPython/Runtime/CompiledLoader.cs b/src/core/IronPython/Runtime/CompiledLoader.cs index 06f29cb3e..cf802eff5 100644 --- a/src/core/IronPython/Runtime/CompiledLoader.cs +++ b/src/core/IronPython/Runtime/CompiledLoader.cs @@ -2,14 +2,15 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Collections.Generic; using System.IO; -using Microsoft.Scripting; - using IronPython.Compiler; -using IronPython.Runtime.Operations; + +using Microsoft.Scripting; namespace IronPython.Runtime { public class CompiledLoader { @@ -30,11 +31,11 @@ internal void AddScriptCode(ScriptCode code) { } } - public ModuleLoader find_module(CodeContext/*!*/ context, string fullname, PythonList path = null) { - if (_codes.TryGetValue(fullname, out OnDiskScriptCode sc)) { + public ModuleLoader? find_module(CodeContext/*!*/ context, string fullname, PythonList? path = null) { + if (_codes.TryGetValue(fullname, out OnDiskScriptCode? sc)) { int sep = fullname.LastIndexOf('.'); string name = fullname; - string parentName = null; + string? parentName = null; if (sep != -1) { parentName = fullname.Substring(0, sep); name = fullname.Substring(sep + 1); diff --git a/src/core/IronPython/Runtime/DictionaryOps.cs b/src/core/IronPython/Runtime/DictionaryOps.cs index 6743aca33..868165ede 100644 --- a/src/core/IronPython/Runtime/DictionaryOps.cs +++ b/src/core/IronPython/Runtime/DictionaryOps.cs @@ -2,20 +2,18 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System; +#nullable enable + using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.CompilerServices; using System.Text; -using Microsoft.Scripting; -using Microsoft.Scripting.Runtime; - -using IronPython.Runtime.Binding; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; +using Microsoft.Scripting.Runtime; + namespace IronPython.Runtime { /// /// Provides both helpers for implementing Python dictionaries as well @@ -29,8 +27,8 @@ public static class DictionaryOps { // Dictionary has an odd not-implemented check to support custom dictionaries and therefore // needs a custom __eq__ / __ne__ implementation. - public static string/*!*/ __repr__(CodeContext/*!*/ context, IDictionary self) { - List infinite = PythonOps.GetAndCheckInfinite(self); + public static string/*!*/ __repr__(CodeContext/*!*/ context, IDictionary self) { + List? infinite = PythonOps.GetAndCheckInfinite(self); if (infinite == null) { return "{...}"; } @@ -41,7 +39,7 @@ public static class DictionaryOps { StringBuilder buf = new StringBuilder(); buf.Append("{"); bool first = true; - foreach (KeyValuePair kv in self) { + foreach (KeyValuePair kv in self) { if (first) first = false; else buf.Append(", "); @@ -66,7 +64,7 @@ public static class DictionaryOps { } } - public static object get(PythonDictionary self, object key, object defaultValue = null) { + public static object? get(PythonDictionary self, object key, object? defaultValue = null) { if (self.TryGetValueNoMissing(key, out object ret)) return ret; return defaultValue; } @@ -110,11 +108,11 @@ public static PythonTuple popitem(PythonDictionary self) { throw PythonOps.KeyError("dictionary is empty"); } - public static object setdefault(PythonDictionary self, object key) { + public static object? setdefault(PythonDictionary self, object key) { return setdefault(self, key, null); } - public static object setdefault(PythonDictionary self, object key, object defaultValue) { + public static object? setdefault(PythonDictionary self, object key, object? defaultValue) { if (self.TryGetValueNoMissing(key, out object ret)) return ret; self.SetItem(key, defaultValue); return defaultValue; @@ -136,7 +134,7 @@ private static void SlowUpdate(CodeContext/*!*/ context, PythonDictionary/*!*/ s while (e.MoveNext()) { self._storage.Add(ref self._storage, e.Key, e.Value); } - } else if (PythonOps.TryGetBoundAttr(other, "keys", out object keysFunc)) { + } else if (PythonOps.TryGetBoundAttr(other, "keys", out object? keysFunc)) { // user defined dictionary IEnumerator i = PythonOps.GetEnumerator(context, PythonCalls.Call(context, keysFunc)); while (i.MoveNext()) { @@ -160,9 +158,8 @@ private static void SlowUpdate(CodeContext/*!*/ context, PythonDictionary/*!*/ s #region Dictionary Helper APIs - internal static bool TryGetValueVirtual(CodeContext context, PythonDictionary self, object key, ref object DefaultGetItem, out object value) { + internal static bool TryGetValueVirtual(CodeContext context, PythonDictionary self, object key, ref object DefaultGetItem, out object? value) { if (self is IPythonObject sdo) { - Debug.Assert(sdo != null); PythonType myType = sdo.PythonType; PythonTypeSlot dts; diff --git a/src/core/IronPython/Runtime/DictionaryTypeInfoAttribute.cs b/src/core/IronPython/Runtime/DictionaryTypeInfoAttribute.cs index 583d8269c..5e5604573 100644 --- a/src/core/IronPython/Runtime/DictionaryTypeInfoAttribute.cs +++ b/src/core/IronPython/Runtime/DictionaryTypeInfoAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Runtime { diff --git a/src/core/IronPython/Runtime/DontMapGetMemberNamesToDirAttribute.cs b/src/core/IronPython/Runtime/DontMapGetMemberNamesToDirAttribute.cs index ca2bcef7d..6b24f9913 100644 --- a/src/core/IronPython/Runtime/DontMapGetMemberNamesToDirAttribute.cs +++ b/src/core/IronPython/Runtime/DontMapGetMemberNamesToDirAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Runtime { diff --git a/src/core/IronPython/Runtime/DontMapICollectionToLenAttribute.cs b/src/core/IronPython/Runtime/DontMapICollectionToLenAttribute.cs index e279eb2f4..eda64b413 100644 --- a/src/core/IronPython/Runtime/DontMapICollectionToLenAttribute.cs +++ b/src/core/IronPython/Runtime/DontMapICollectionToLenAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Runtime { diff --git a/src/core/IronPython/Runtime/DontMapIDisposableToContextManagerAttribute.cs b/src/core/IronPython/Runtime/DontMapIDisposableToContextManagerAttribute.cs index 70e7744c7..f0230c847 100644 --- a/src/core/IronPython/Runtime/DontMapIDisposableToContextManagerAttribute.cs +++ b/src/core/IronPython/Runtime/DontMapIDisposableToContextManagerAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Runtime { diff --git a/src/core/IronPython/Runtime/DontMapIEnumerableToContainsAttribute.cs b/src/core/IronPython/Runtime/DontMapIEnumerableToContainsAttribute.cs index d2c362f2a..b2546c4cd 100644 --- a/src/core/IronPython/Runtime/DontMapIEnumerableToContainsAttribute.cs +++ b/src/core/IronPython/Runtime/DontMapIEnumerableToContainsAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Runtime { diff --git a/src/core/IronPython/Runtime/DontMapIEnumerableToIterAttribute.cs b/src/core/IronPython/Runtime/DontMapIEnumerableToIterAttribute.cs index bf608ab22..c75cd7684 100644 --- a/src/core/IronPython/Runtime/DontMapIEnumerableToIterAttribute.cs +++ b/src/core/IronPython/Runtime/DontMapIEnumerableToIterAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Runtime { diff --git a/src/core/IronPython/Runtime/ErrorCodes.cs b/src/core/IronPython/Runtime/ErrorCodes.cs index 3718dcf28..be3457707 100644 --- a/src/core/IronPython/Runtime/ErrorCodes.cs +++ b/src/core/IronPython/Runtime/ErrorCodes.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + namespace IronPython.Runtime { public static class ErrorCodes { // The error flags diff --git a/src/core/IronPython/Runtime/Exceptions/AttributeErrorException.cs b/src/core/IronPython/Runtime/Exceptions/AttributeErrorException.cs index ec4a18038..3af1e3bd3 100644 --- a/src/core/IronPython/Runtime/Exceptions/AttributeErrorException.cs +++ b/src/core/IronPython/Runtime/Exceptions/AttributeErrorException.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Collections.Generic; using System.Runtime.Serialization; @@ -13,12 +15,11 @@ namespace IronPython.Runtime.Exceptions { // *** BEGIN GENERATED CODE *** // generated by function: gen_one_exception_specialized from: generate_exceptions.py - [Serializable] public class AttributeErrorException : MissingMemberException, IPythonAwareException { - private PythonExceptions.BaseException _pyExceptionObject; - private List _frames; - private TraceBack _traceback; + private PythonExceptions.BaseException? _pyExceptionObject; + private List? _frames; + private TraceBack? _traceback; public AttributeErrorException() : base() { } public AttributeErrorException(string msg) : base(msg) { } @@ -36,23 +37,22 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } #endif - PythonExceptions.BaseException IPythonAwareException.PythonException { + PythonExceptions.BaseException? IPythonAwareException.PythonException { get { return _pyExceptionObject; } set { _pyExceptionObject = value; } } - List IPythonAwareException.Frames { + List? IPythonAwareException.Frames { get { return _frames; } set { _frames = value; } } - TraceBack IPythonAwareException.TraceBack { + TraceBack? IPythonAwareException.TraceBack { get { return _traceback; } set { _traceback = value; } } } - // *** END GENERATED CODE *** #endregion diff --git a/src/core/IronPython/Runtime/Exceptions/GeneratorExitException.cs b/src/core/IronPython/Runtime/Exceptions/GeneratorExitException.cs index 9a0a1e7b9..6a08b5e63 100644 --- a/src/core/IronPython/Runtime/Exceptions/GeneratorExitException.cs +++ b/src/core/IronPython/Runtime/Exceptions/GeneratorExitException.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Runtime.Serialization; diff --git a/src/core/IronPython/Runtime/Exceptions/IndentationException.cs b/src/core/IronPython/Runtime/Exceptions/IndentationException.cs index 508522cb0..843f12098 100644 --- a/src/core/IronPython/Runtime/Exceptions/IndentationException.cs +++ b/src/core/IronPython/Runtime/Exceptions/IndentationException.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Runtime.Serialization; using System.Security; diff --git a/src/core/IronPython/Runtime/Exceptions/TabException.cs b/src/core/IronPython/Runtime/Exceptions/TabException.cs index 7d0815d86..48fb234a7 100644 --- a/src/core/IronPython/Runtime/Exceptions/TabException.cs +++ b/src/core/IronPython/Runtime/Exceptions/TabException.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Dynamic; using Microsoft.Scripting; diff --git a/src/core/IronPython/Runtime/Exceptions/ValueErrorException.cs b/src/core/IronPython/Runtime/Exceptions/ValueErrorException.cs index 9b86c8201..e02ba932c 100644 --- a/src/core/IronPython/Runtime/Exceptions/ValueErrorException.cs +++ b/src/core/IronPython/Runtime/Exceptions/ValueErrorException.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Collections.Generic; using System.Runtime.Serialization; @@ -16,9 +18,9 @@ namespace IronPython.Runtime.Exceptions { [Serializable] public class ValueErrorException : ArgumentException, IPythonAwareException { - private PythonExceptions.BaseException _pyExceptionObject; - private List _frames; - private TraceBack _traceback; + private PythonExceptions.BaseException? _pyExceptionObject; + private List? _frames; + private TraceBack? _traceback; public ValueErrorException() : base() { } public ValueErrorException(string msg) : base(msg) { } @@ -36,23 +38,22 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } #endif - PythonExceptions.BaseException IPythonAwareException.PythonException { + PythonExceptions.BaseException? IPythonAwareException.PythonException { get { return _pyExceptionObject; } set { _pyExceptionObject = value; } } - List IPythonAwareException.Frames { + List? IPythonAwareException.Frames { get { return _frames; } set { _frames = value; } } - TraceBack IPythonAwareException.TraceBack { + TraceBack? IPythonAwareException.TraceBack { get { return _traceback; } set { _traceback = value; } } } - // *** END GENERATED CODE *** #endregion diff --git a/src/core/IronPython/Runtime/FunctionAttributes.cs b/src/core/IronPython/Runtime/FunctionAttributes.cs index 6ffc0c85b..45edf190e 100644 --- a/src/core/IronPython/Runtime/FunctionAttributes.cs +++ b/src/core/IronPython/Runtime/FunctionAttributes.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Runtime { diff --git a/src/core/IronPython/Runtime/IParameterSequence.cs b/src/core/IronPython/Runtime/IParameterSequence.cs index 2224109f4..7de27da16 100644 --- a/src/core/IronPython/Runtime/IParameterSequence.cs +++ b/src/core/IronPython/Runtime/IParameterSequence.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + namespace IronPython.Runtime { /// /// Represents a sequence which may have been provided as a set of parameters to an indexer. diff --git a/src/core/IronPython/Runtime/Implementation.cs b/src/core/IronPython/Runtime/Implementation.cs index cc244460f..5d875f844 100644 --- a/src/core/IronPython/Runtime/Implementation.cs +++ b/src/core/IronPython/Runtime/Implementation.cs @@ -2,12 +2,11 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; -using System.Linq; using System.Reflection; -using IronPython.Runtime.Operations; - namespace IronPython.Runtime { [PythonType("sys.version_info")] public class VersionInfo : PythonTuple { @@ -98,12 +97,12 @@ static string GetShortReleaseLevel(string releaselevel) { static CurrentVersion() { var assembly = typeof(CurrentVersion).Assembly; - var version = new AssemblyName(assembly.FullName).Version; // don't use Assembly.GetName since it fails in partial trust scenarios + var version = new AssemblyName(assembly.FullName!).Version!; // don't use Assembly.GetName since it fails in partial trust scenarios Major = version.Major; Minor = version.Minor; Micro = version.Build; Series = version.ToString(2); - var split = assembly.GetCustomAttribute().InformationalVersion.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + var split = assembly.GetCustomAttribute()!.InformationalVersion.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); ReleaseLevel = split[split.Length - 2]; ReleaseSerial = int.Parse(split[split.Length - 1]); DisplayName = $"IronPython {GetVersionString(Major, Minor, Micro, ReleaseLevel, ReleaseSerial)}"; diff --git a/src/core/IronPython/Runtime/InstancedModuleDictionaryStorage.cs b/src/core/IronPython/Runtime/InstancedModuleDictionaryStorage.cs index d1682025c..93cedcf97 100644 --- a/src/core/IronPython/Runtime/InstancedModuleDictionaryStorage.cs +++ b/src/core/IronPython/Runtime/InstancedModuleDictionaryStorage.cs @@ -2,8 +2,10 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System; +#nullable enable + using System.Collections.Generic; + using IronPython.Compiler; namespace IronPython.Runtime { diff --git a/src/core/IronPython/Runtime/KwCallInfo.cs b/src/core/IronPython/Runtime/KwCallInfo.cs index a3a8afa11..cf9f72973 100644 --- a/src/core/IronPython/Runtime/KwCallInfo.cs +++ b/src/core/IronPython/Runtime/KwCallInfo.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + namespace IronPython.Runtime { public sealed class KwCallInfo { private readonly object[] _args; diff --git a/src/core/IronPython/Runtime/MaybeNotImplementedAttribute.cs b/src/core/IronPython/Runtime/MaybeNotImplementedAttribute.cs index 274d65e90..19a57aced 100644 --- a/src/core/IronPython/Runtime/MaybeNotImplementedAttribute.cs +++ b/src/core/IronPython/Runtime/MaybeNotImplementedAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Runtime { diff --git a/src/core/IronPython/Runtime/MemoryStreamContentProvider.cs b/src/core/IronPython/Runtime/MemoryStreamContentProvider.cs index 4fd4e5704..17111b2e8 100644 --- a/src/core/IronPython/Runtime/MemoryStreamContentProvider.cs +++ b/src/core/IronPython/Runtime/MemoryStreamContentProvider.cs @@ -2,8 +2,11 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.IO; + using Microsoft.Scripting; using Microsoft.Scripting.Utils; diff --git a/src/core/IronPython/Runtime/MissingParameter.cs b/src/core/IronPython/Runtime/MissingParameter.cs index 0c3fbc104..be5e3f350 100644 --- a/src/core/IronPython/Runtime/MissingParameter.cs +++ b/src/core/IronPython/Runtime/MissingParameter.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + namespace IronPython.Runtime { public sealed class MissingParameter { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] diff --git a/src/core/IronPython/Runtime/ModuleGlobalCache.cs b/src/core/IronPython/Runtime/ModuleGlobalCache.cs index f6c55203a..9ce7bfc95 100644 --- a/src/core/IronPython/Runtime/ModuleGlobalCache.cs +++ b/src/core/IronPython/Runtime/ModuleGlobalCache.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Diagnostics; diff --git a/src/core/IronPython/Runtime/ModuleLoader.cs b/src/core/IronPython/Runtime/ModuleLoader.cs index 3966d0157..82e91780d 100644 --- a/src/core/IronPython/Runtime/ModuleLoader.cs +++ b/src/core/IronPython/Runtime/ModuleLoader.cs @@ -2,17 +2,18 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System; -using Microsoft.Scripting; +#nullable enable + using IronPython.Compiler; namespace IronPython.Runtime { public sealed class ModuleLoader { private readonly OnDiskScriptCode _sc; - private readonly string _parentName, _name; + private readonly string? _parentName; + private readonly string _name; - internal ModuleLoader(OnDiskScriptCode sc, string parentName, string name) { + internal ModuleLoader(OnDiskScriptCode sc, string? parentName, string name) { _sc = sc; _parentName = parentName; _name = name; @@ -27,7 +28,7 @@ public PythonModule load_module(CodeContext/*!*/ context, string fullName) { if (_parentName != null) { // if we are a module in a package update the parent package w/ our scope. - object parent; + object? parent; if (pc.SystemStateModules.TryGetValue(_parentName, out parent)) { if (parent is PythonModule s) { s.__dict__[_name] = newContext.ModuleContext.Module; @@ -38,5 +39,4 @@ public PythonModule load_module(CodeContext/*!*/ context, string fullName) { return newContext.ModuleContext.Module; } } - } diff --git a/src/core/IronPython/Runtime/ModuleOptions.cs b/src/core/IronPython/Runtime/ModuleOptions.cs index 9d051028c..a49939153 100644 --- a/src/core/IronPython/Runtime/ModuleOptions.cs +++ b/src/core/IronPython/Runtime/ModuleOptions.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; -using System.Collections.Generic; -using System.Text; namespace IronPython.Runtime { [Flags] diff --git a/src/core/IronPython/Runtime/NameType.cs b/src/core/IronPython/Runtime/NameType.cs index 1427d6773..5f93ccc62 100644 --- a/src/core/IronPython/Runtime/NameType.cs +++ b/src/core/IronPython/Runtime/NameType.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Runtime { diff --git a/src/core/IronPython/Runtime/Operations/BoolOps.cs b/src/core/IronPython/Runtime/Operations/BoolOps.cs index 9654968e3..2e72c603f 100644 --- a/src/core/IronPython/Runtime/Operations/BoolOps.cs +++ b/src/core/IronPython/Runtime/Operations/BoolOps.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Numerics; diff --git a/src/core/IronPython/Runtime/Operations/FloatOps.Generated.cs b/src/core/IronPython/Runtime/Operations/FloatOps.Generated.cs index 113d646c0..bd670bac3 100644 --- a/src/core/IronPython/Runtime/Operations/FloatOps.Generated.cs +++ b/src/core/IronPython/Runtime/Operations/FloatOps.Generated.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Numerics; using System.Runtime.CompilerServices; diff --git a/src/core/IronPython/Runtime/Operations/FloatOps.cs b/src/core/IronPython/Runtime/Operations/FloatOps.cs index 61df44832..51cf840ea 100644 --- a/src/core/IronPython/Runtime/Operations/FloatOps.cs +++ b/src/core/IronPython/Runtime/Operations/FloatOps.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Diagnostics; using System.Globalization; @@ -21,7 +23,7 @@ namespace IronPython.Runtime.Operations { public static partial class DoubleOps { - private static Regex _fromHexRegex; + private static Regex? _fromHexRegex; [StaticExtensionMethod] public static object __new__(CodeContext/*!*/ context, PythonType cls) { @@ -67,7 +69,7 @@ public static object __new__(CodeContext/*!*/ context, PythonType cls, object x) } } - internal static bool TryToFloat(CodeContext context, object/*?*/ value, out double result) { + internal static bool TryToFloat(CodeContext context, object? value, out double result) { if (value is double d) { result = d; } else if (value is int i) { @@ -80,7 +82,7 @@ internal static bool TryToFloat(CodeContext context, object/*?*/ value, out doub result = ed.Value; } else if (value is Extensible ebi) { result = BigIntegerOps.ToDouble(ebi.Value); - } else if (PythonOps.TryToIndex(value, out object ireal)) { // Python 3.8: fall back on __index__ + } else if (PythonOps.TryToIndex(value, out object? ireal)) { // Python 3.8: fall back on __index__ result = ireal switch { int ii => ii, BigInteger bii => BigIntegerOps.ToDouble(bii), @@ -91,7 +93,7 @@ internal static bool TryToFloat(CodeContext context, object/*?*/ value, out doub } return true; - static bool TryInvokeFloat(CodeContext context, object/*?*/ o, out double result) { + static bool TryInvokeFloat(CodeContext context, object? o, out double result) { if (PythonTypeOps.TryInvokeUnaryOperator(context, o, "__float__", out object retobj)) { switch (retobj) { case double d: @@ -208,7 +210,7 @@ public static object fromhex(CodeContext/*!*/ context, PythonType/*!*/ cls, stri return zeroRes; } - return PythonCalls.Call(cls, zeroRes); + return PythonCalls.Call(cls, zeroRes)!; } // integer value is too big, no way we're fitting this in. throw HexStringOverflow(); @@ -313,7 +315,7 @@ public static object fromhex(CodeContext/*!*/ context, PythonType/*!*/ cls, stri return res; } - return PythonCalls.Call(cls, res); + return PythonCalls.Call(cls, res)!; } private static double? TryParseSpecialFloat(string self) { diff --git a/src/core/IronPython/Runtime/Operations/IntOps.Generated.cs b/src/core/IronPython/Runtime/Operations/IntOps.Generated.cs index 4a6c512df..071e22a63 100644 --- a/src/core/IronPython/Runtime/Operations/IntOps.Generated.cs +++ b/src/core/IronPython/Runtime/Operations/IntOps.Generated.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Globalization; using System.Numerics; diff --git a/src/core/IronPython/Runtime/Operations/MarshalOps.cs b/src/core/IronPython/Runtime/Operations/MarshalOps.cs index 5c043c803..5ccfa6213 100644 --- a/src/core/IronPython/Runtime/Operations/MarshalOps.cs +++ b/src/core/IronPython/Runtime/Operations/MarshalOps.cs @@ -1,4 +1,8 @@ -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using System; using System.Collections.Generic; using System.Globalization; using System.Numerics; diff --git a/src/core/IronPython/Runtime/Operations/PythonOps.Generated.cs b/src/core/IronPython/Runtime/Operations/PythonOps.Generated.cs index 016dcc6dd..44b377549 100644 --- a/src/core/IronPython/Runtime/Operations/PythonOps.Generated.cs +++ b/src/core/IronPython/Runtime/Operations/PythonOps.Generated.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.ComponentModel; @@ -15,147 +17,147 @@ public static partial class PythonOps { // generated by function: factory_gen from: generate_exceptions.py - public static Exception ImportError(string format, params object[] args) { + public static Exception ImportError(string format, params object?[] args) { return new ImportException(string.Format(format, args)); } - public static Exception RuntimeError(string format, params object[] args) { + public static Exception RuntimeError(string format, params object?[] args) { return new RuntimeException(string.Format(format, args)); } - public static Exception UnicodeTranslateError(string format, params object[] args) { + public static Exception UnicodeTranslateError(string format, params object?[] args) { return new UnicodeTranslateException(string.Format(format, args)); } - public static Exception PendingDeprecationWarning(string format, params object[] args) { + public static Exception PendingDeprecationWarning(string format, params object?[] args) { return new PendingDeprecationWarningException(string.Format(format, args)); } - public static Exception LookupError(string format, params object[] args) { + public static Exception LookupError(string format, params object?[] args) { return new LookupException(string.Format(format, args)); } - public static Exception OSError(string format, params object[] args) { + public static Exception OSError(string format, params object?[] args) { return new OSException(string.Format(format, args)); } - public static Exception DeprecationWarning(string format, params object[] args) { + public static Exception DeprecationWarning(string format, params object?[] args) { return new DeprecationWarningException(string.Format(format, args)); } - public static Exception UnicodeError(string format, params object[] args) { + public static Exception UnicodeError(string format, params object?[] args) { return new UnicodeException(string.Format(format, args)); } - public static Exception FloatingPointError(string format, params object[] args) { + public static Exception FloatingPointError(string format, params object?[] args) { return new FloatingPointException(string.Format(format, args)); } - public static Exception ReferenceError(string format, params object[] args) { + public static Exception ReferenceError(string format, params object?[] args) { return new ReferenceException(string.Format(format, args)); } - public static Exception FutureWarning(string format, params object[] args) { + public static Exception FutureWarning(string format, params object?[] args) { return new FutureWarningException(string.Format(format, args)); } - public static Exception AssertionError(string format, params object[] args) { + public static Exception AssertionError(string format, params object?[] args) { return new AssertionException(string.Format(format, args)); } - public static Exception RuntimeWarning(string format, params object[] args) { + public static Exception RuntimeWarning(string format, params object?[] args) { return new RuntimeWarningException(string.Format(format, args)); } - public static Exception ImportWarning(string format, params object[] args) { + public static Exception ImportWarning(string format, params object?[] args) { return new ImportWarningException(string.Format(format, args)); } - public static Exception UserWarning(string format, params object[] args) { + public static Exception UserWarning(string format, params object?[] args) { return new UserWarningException(string.Format(format, args)); } - public static Exception SyntaxWarning(string format, params object[] args) { + public static Exception SyntaxWarning(string format, params object?[] args) { return new SyntaxWarningException(string.Format(format, args)); } - public static Exception UnicodeWarning(string format, params object[] args) { + public static Exception UnicodeWarning(string format, params object?[] args) { return new UnicodeWarningException(string.Format(format, args)); } - public static Exception StopIteration(string format, params object[] args) { + public static Exception StopIteration(string format, params object?[] args) { return new StopIterationException(string.Format(format, args)); } - public static Exception BytesWarning(string format, params object[] args) { + public static Exception BytesWarning(string format, params object?[] args) { return new BytesWarningException(string.Format(format, args)); } - public static Exception BufferError(string format, params object[] args) { + public static Exception BufferError(string format, params object?[] args) { return new BufferException(string.Format(format, args)); } - public static Exception ResourceWarning(string format, params object[] args) { + public static Exception ResourceWarning(string format, params object?[] args) { return new ResourceWarningException(string.Format(format, args)); } - public static Exception FileExistsError(string format, params object[] args) { + public static Exception FileExistsError(string format, params object?[] args) { return new FileExistsException(string.Format(format, args)); } - public static Exception BlockingIOError(string format, params object[] args) { + public static Exception BlockingIOError(string format, params object?[] args) { return new BlockingIOException(string.Format(format, args)); } - public static Exception NotADirectoryError(string format, params object[] args) { + public static Exception NotADirectoryError(string format, params object?[] args) { return new NotADirectoryException(string.Format(format, args)); } - public static Exception InterruptedError(string format, params object[] args) { + public static Exception InterruptedError(string format, params object?[] args) { return new InterruptedException(string.Format(format, args)); } - public static Exception ChildProcessError(string format, params object[] args) { + public static Exception ChildProcessError(string format, params object?[] args) { return new ChildProcessException(string.Format(format, args)); } - public static Exception IsADirectoryError(string format, params object[] args) { + public static Exception IsADirectoryError(string format, params object?[] args) { return new IsADirectoryException(string.Format(format, args)); } - public static Exception ProcessLookupError(string format, params object[] args) { + public static Exception ProcessLookupError(string format, params object?[] args) { return new ProcessLookupException(string.Format(format, args)); } - public static Exception ConnectionError(string format, params object[] args) { + public static Exception ConnectionError(string format, params object?[] args) { return new ConnectionException(string.Format(format, args)); } - public static Exception ConnectionAbortedError(string format, params object[] args) { + public static Exception ConnectionAbortedError(string format, params object?[] args) { return new ConnectionAbortedException(string.Format(format, args)); } - public static Exception BrokenPipeError(string format, params object[] args) { + public static Exception BrokenPipeError(string format, params object?[] args) { return new BrokenPipeException(string.Format(format, args)); } - public static Exception ConnectionRefusedError(string format, params object[] args) { + public static Exception ConnectionRefusedError(string format, params object?[] args) { return new ConnectionRefusedException(string.Format(format, args)); } - public static Exception ConnectionResetError(string format, params object[] args) { + public static Exception ConnectionResetError(string format, params object?[] args) { return new ConnectionResetException(string.Format(format, args)); } - public static Exception RecursionError(string format, params object[] args) { + public static Exception RecursionError(string format, params object?[] args) { return new RecursionException(string.Format(format, args)); } - public static Exception StopAsyncIteration(string format, params object[] args) { + public static Exception StopAsyncIteration(string format, params object?[] args) { return new StopAsyncIterationException(string.Format(format, args)); } - public static Exception ModuleNotFoundError(string format, params object[] args) { + public static Exception ModuleNotFoundError(string format, params object?[] args) { return new ModuleNotFoundException(string.Format(format, args)); } diff --git a/src/core/IronPython/Runtime/Operations/StringOps.cs b/src/core/IronPython/Runtime/Operations/StringOps.cs index 36259c804..fd8ac3136 100644 --- a/src/core/IronPython/Runtime/Operations/StringOps.cs +++ b/src/core/IronPython/Runtime/Operations/StringOps.cs @@ -1219,8 +1219,11 @@ private static void AppendValueForTranslate(this StringBuilder ret, object? mapp return; case int mappedInt: if (mappedInt > 0xFFFF) { - // TODO: change to a ValueError in Python 3.5 +#if PYTHON_34 throw PythonOps.TypeError("character mapping must be in range(0x10000)"); +#else + throw PythonOps.ValueError("character mapping must be in range(0x10000)"); +#endif } ret.Append((char)mappedInt); break; diff --git a/src/core/IronPython/Runtime/PlatformsAttribute.cs b/src/core/IronPython/Runtime/PlatformsAttribute.cs index c8c8c5789..11d2910fe 100644 --- a/src/core/IronPython/Runtime/PlatformsAttribute.cs +++ b/src/core/IronPython/Runtime/PlatformsAttribute.cs @@ -2,7 +2,10 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace IronPython.Runtime { @@ -23,9 +26,9 @@ public enum PlatformFamily { public static readonly PlatformID[] WindowsFamily = { PlatformID.Win32NT, PlatformID.Win32S, PlatformID.Win32Windows, PlatformID.WinCE, PlatformID.Xbox }; public static readonly PlatformID[] UnixFamily = { PlatformID.MacOSX, PlatformID.Unix }; - public PlatformID[] ValidPlatforms { get; protected set; } + public PlatformID[] ValidPlatforms { get; protected set; } = []; - public bool IsPlatformValid => ValidPlatforms == null || ValidPlatforms.Length == 0 || Array.IndexOf(ValidPlatforms, ActualPlatform) >= 0; + public bool IsPlatformValid => ValidPlatforms.Length == 0 || Array.IndexOf(ValidPlatforms, ActualPlatform) >= 0; private static PlatformID ActualPlatform => RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? PlatformID.Unix : @@ -43,4 +46,4 @@ protected void SetValidPlatforms(PlatformFamily validPlatformFamily) { } } } -} \ No newline at end of file +} diff --git a/src/core/IronPython/Runtime/Profiler.cs b/src/core/IronPython/Runtime/Profiler.cs index bc0d245e4..022282087 100644 --- a/src/core/IronPython/Runtime/Profiler.cs +++ b/src/core/IronPython/Runtime/Profiler.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using MSAst = System.Linq.Expressions; using System; @@ -222,7 +224,7 @@ internal MSAst.Expression AddOuterProfiling(MSAst.Expression/*!*/ body, MSAst.Pa tick, Ast.Call( Ast.Constant(this, typeof(Profiler)), - typeof(Profiler).GetMethod(nameof(Profiler.StartCall)), + typeof(Profiler).GetMethod(nameof(Profiler.StartCall))!, AstUtils.Constant(profileIndex) ) ), @@ -231,7 +233,7 @@ internal MSAst.Expression AddOuterProfiling(MSAst.Expression/*!*/ body, MSAst.Pa ).Finally( Ast.Call( Ast.Constant(this, typeof(Profiler)), - typeof(Profiler).GetMethod(nameof(Profiler.FinishCall)), + typeof(Profiler).GetMethod(nameof(Profiler.FinishCall))!, AstUtils.Constant(profileIndex), tick ) @@ -245,7 +247,7 @@ internal MSAst.Expression AddInnerProfiling(MSAst.Expression/*!*/ body, MSAst.Pa tick, Ast.Call( Ast.Constant(this, typeof(Profiler)), - typeof(Profiler).GetMethod(nameof(Profiler.StartNestedCall)), + typeof(Profiler).GetMethod(nameof(Profiler.StartNestedCall))!, AstUtils.Constant(profileIndex), tick ) @@ -257,7 +259,7 @@ internal MSAst.Expression AddInnerProfiling(MSAst.Expression/*!*/ body, MSAst.Pa tick, Ast.Call( Ast.Constant(this, typeof(Profiler)), - typeof(Profiler).GetMethod(nameof(Profiler.FinishNestedCall)), + typeof(Profiler).GetMethod(nameof(Profiler.FinishNestedCall))!, AstUtils.Constant(profileIndex), tick ) diff --git a/src/core/IronPython/Runtime/PythonContext.Generated.cs b/src/core/IronPython/Runtime/PythonContext.Generated.cs index 9942356bc..5398e7bef 100644 --- a/src/core/IronPython/Runtime/PythonContext.Generated.cs +++ b/src/core/IronPython/Runtime/PythonContext.Generated.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Runtime.CompilerServices; using System.Threading; diff --git a/src/core/IronPython/Runtime/PythonContext.cs b/src/core/IronPython/Runtime/PythonContext.cs index 505942a41..0e4efbdee 100644 --- a/src/core/IronPython/Runtime/PythonContext.cs +++ b/src/core/IronPython/Runtime/PythonContext.cs @@ -299,7 +299,9 @@ void BootstrapImportLib() { try { var _frozen_importlib = LoadModuleFromResource("_frozen_importlib", "IronPython.Modules._bootstrap.py"); - +#if PYTHON_36_OR_GREATER + LoadModuleFromResource("_frozen_importlib_external", "IronPython.Modules._bootstrap_external.py"); +#endif PythonOps.Invoke(SharedClsContext, _frozen_importlib, "_install", SystemState, GetBuiltinModule("_imp")); } catch { } diff --git a/src/core/IronPython/Runtime/PythonDictionary.cs b/src/core/IronPython/Runtime/PythonDictionary.cs index bcf9a9256..978350584 100644 --- a/src/core/IronPython/Runtime/PythonDictionary.cs +++ b/src/core/IronPython/Runtime/PythonDictionary.cs @@ -1053,6 +1053,7 @@ void ICollection.CopyTo(Array array, int index) { #region ICodeFormattable Members public string __repr__(CodeContext context) { +#if PYTHON_34 StringBuilder res = new StringBuilder(20); res.Append("dict_values(["); string comma = ""; @@ -1069,6 +1070,36 @@ public string __repr__(CodeContext context) { res.Append("])"); return res.ToString(); +#else + List infinite = PythonOps.GetAndCheckInfinite(this); + if (infinite == null) { + return "..."; + } + + int index = infinite.Count; + infinite.Add(this); + try { + StringBuilder res = new StringBuilder(20); + res.Append("dict_values(["); + string comma = ""; + foreach (object value in this) { + res.Append(comma); + comma = ", "; + try { + PythonOps.FunctionPushFrame(context.LanguageContext); + res.Append(PythonOps.Repr(context, value)); + } finally { + PythonOps.FunctionPopFrame(); + } + } + res.Append("])"); + + return res.ToString(); + } finally { + Debug.Assert(index == infinite.Count - 1); + infinite.RemoveAt(index); + } +#endif } #endregion @@ -1772,6 +1803,7 @@ public override bool Equals(object obj) { #region ICodeFormattable Members public string __repr__(CodeContext context) { +#if PYTHON_34 StringBuilder res = new StringBuilder(20); res.Append("dict_items(["); string comma = ""; @@ -1788,6 +1820,36 @@ public string __repr__(CodeContext context) { res.Append("])"); return res.ToString(); +#else + List infinite = PythonOps.GetAndCheckInfinite(this); + if (infinite == null) { + return "..."; + } + + int index = infinite.Count; + infinite.Add(this); + try { + StringBuilder res = new StringBuilder(20); + res.Append("dict_items(["); + string comma = ""; + foreach (object item in this) { + res.Append(comma); + comma = ", "; + try { + PythonOps.FunctionPushFrame(context.LanguageContext); + res.Append(PythonOps.Repr(context, item)); + } finally { + PythonOps.FunctionPopFrame(); + } + } + res.Append("])"); + + return res.ToString(); + } finally { + Debug.Assert(index == infinite.Count - 1); + infinite.RemoveAt(index); + } +#endif } #endregion diff --git a/src/core/IronPython/Runtime/PythonDocumentationProvider.cs b/src/core/IronPython/Runtime/PythonDocumentationProvider.cs index adc89c53b..e668848bd 100644 --- a/src/core/IronPython/Runtime/PythonDocumentationProvider.cs +++ b/src/core/IronPython/Runtime/PythonDocumentationProvider.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Collections.Generic; using System.Reflection; @@ -84,8 +86,7 @@ private static MemberDoc MakeMemberDoc(string name, object value, bool fromClass kind = fromClass ? MemberKind.Method : MemberKind.Function; } else if (value is BuiltinMethodDescriptor || value is Method) { kind = MemberKind.Method; - } else if (value is PythonType) { - var pt = value as PythonType; + } else if (value is PythonType pt) { if (pt.IsSystemType && pt.UnderlyingSystemType.IsEnum) { kind = MemberKind.Enum; } else { diff --git a/src/core/IronPython/Runtime/PythonHiddenAttribute.cs b/src/core/IronPython/Runtime/PythonHiddenAttribute.cs index f9d8d0453..0773ee0a8 100644 --- a/src/core/IronPython/Runtime/PythonHiddenAttribute.cs +++ b/src/core/IronPython/Runtime/PythonHiddenAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Reflection; diff --git a/src/core/IronPython/Runtime/PythonHiddenBaseClassAttribute.cs b/src/core/IronPython/Runtime/PythonHiddenBaseClassAttribute.cs index 30cd90a43..989b46685 100644 --- a/src/core/IronPython/Runtime/PythonHiddenBaseClassAttribute.cs +++ b/src/core/IronPython/Runtime/PythonHiddenBaseClassAttribute.cs @@ -1,7 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +#nullable enable + +using System; namespace IronPython.Runtime { /// diff --git a/src/core/IronPython/Runtime/PythonModuleAttribute.cs b/src/core/IronPython/Runtime/PythonModuleAttribute.cs index 8a4be79e8..8e89c149a 100644 --- a/src/core/IronPython/Runtime/PythonModuleAttribute.cs +++ b/src/core/IronPython/Runtime/PythonModuleAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using Microsoft.Scripting.Utils; diff --git a/src/core/IronPython/Runtime/PythonNarrowing.cs b/src/core/IronPython/Runtime/PythonNarrowing.cs index 064229482..7604b3370 100644 --- a/src/core/IronPython/Runtime/PythonNarrowing.cs +++ b/src/core/IronPython/Runtime/PythonNarrowing.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using Microsoft.Scripting.Actions.Calls; namespace IronPython.Runtime { diff --git a/src/core/IronPython/Runtime/PythonOptions.cs b/src/core/IronPython/Runtime/PythonOptions.cs index 92125273f..d5dc14385 100644 --- a/src/core/IronPython/Runtime/PythonOptions.cs +++ b/src/core/IronPython/Runtime/PythonOptions.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -123,7 +125,7 @@ public sealed class PythonOptions : LanguageOptions { /// /// Returns a regular expression of Python files which should not be emitted in debug mode. /// - public Regex NoDebug { get; } + public Regex? NoDebug { get; } public bool Quiet { get; } @@ -138,7 +140,7 @@ public PythonOptions() : this(null) { } - public PythonOptions(IDictionary options) + public PythonOptions(IDictionary? options) : base(EnsureSearchPaths(options)) { Arguments = GetStringCollectionOption(options, "Arguments") ?? EmptyStringCollection; @@ -160,7 +162,7 @@ public PythonOptions(IDictionary options) Frames = FullFrames || GetOption(options, "Frames", true); GCStress = GetOption(options, "GCStress", null); Tracing = GetOption(options, "Tracing", false); - NoDebug = GetOption(options, "NoDebug", (Regex)null); + NoDebug = GetOption(options, "NoDebug", (Regex?)null); Quiet = GetOption(options, "Quiet", false); NoImportLib = GetOption(options, "NoImportLib", false); Isolated = GetOption(options, "Isolated", false); @@ -168,7 +170,7 @@ public PythonOptions(IDictionary options) ConsoleSupportLevel = GetEnumOption(options, "ConsoleSupportLevel", SharedIO.SupportLevel.Full); } - private static IDictionary EnsureSearchPaths(IDictionary options) { + private static IDictionary EnsureSearchPaths(IDictionary? options) { if (options == null) { return new Dictionary() { { "SearchPaths", new[] { "." } } }; } else if (!options.ContainsKey("SearchPaths")) { @@ -177,8 +179,8 @@ private static IDictionary EnsureSearchPaths(IDictionary(IDictionary options, string name, T defaultValue) where T : struct, Enum { - if (options != null && options.TryGetValue(name, out object value)) { + private static T GetEnumOption(IDictionary? options, string name, T defaultValue) where T : struct, Enum { + if (options != null && options.TryGetValue(name, out object? value)) { if (value is T variable) { return variable; } diff --git a/src/core/IronPython/Runtime/PythonScopeExtension.cs b/src/core/IronPython/Runtime/PythonScopeExtension.cs index 3adb330b5..ab7b47ec4 100644 --- a/src/core/IronPython/Runtime/PythonScopeExtension.cs +++ b/src/core/IronPython/Runtime/PythonScopeExtension.cs @@ -2,8 +2,10 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System; +#nullable enable + using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.Scripting.Runtime; @@ -18,7 +20,7 @@ namespace IronPython.Runtime { internal class PythonScopeExtension : ScopeExtension { private readonly ModuleContext _modContext; private readonly PythonModule _module; - private Dictionary _objectKeys; + private Dictionary? _objectKeys; public PythonScopeExtension(PythonContext context, Scope scope) : base(scope) { _module = new PythonModule(context, scope); @@ -43,6 +45,7 @@ public PythonModule Module { } } + [MemberNotNull(nameof(_objectKeys))] public Dictionary EnsureObjectKeys() { if (_objectKeys == null) { Interlocked.CompareExchange(ref _objectKeys, new Dictionary(), null); @@ -51,7 +54,7 @@ public Dictionary EnsureObjectKeys() { return _objectKeys; } - public Dictionary ObjectKeys { + public Dictionary? ObjectKeys { get { return _objectKeys; } diff --git a/src/core/IronPython/Runtime/StringFormatter.cs b/src/core/IronPython/Runtime/StringFormatter.cs index bd62147f4..a2d53725c 100644 --- a/src/core/IronPython/Runtime/StringFormatter.cs +++ b/src/core/IronPython/Runtime/StringFormatter.cs @@ -387,8 +387,11 @@ private void WriteConversion() { private object GetIntegerValue(char format, out bool fPos, bool allowDouble = true) { if (!allowDouble && (_opts.Value is float || _opts.Value is double || _opts.Value is Extensible)) { - // TODO: this should fail in 3.5 +#if PYTHON_34 PythonOps.Warn(_context, PythonExceptions.DeprecationWarning, "automatic int conversions have been deprecated"); +#else + throw PythonOps.TypeError($"an integer is required, not {PythonOps.GetPythonTypeName(_opts.Value)}"); +#endif } switch (_opts.Value) { diff --git a/src/core/IronPython/Runtime/Symbols.Generated.cs b/src/core/IronPython/Runtime/Symbols.Generated.cs index 12201afcf..5753aa93a 100644 --- a/src/core/IronPython/Runtime/Symbols.Generated.cs +++ b/src/core/IronPython/Runtime/Symbols.Generated.cs @@ -2,10 +2,11 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; + using IronPython.Runtime.Binding; -using Microsoft.Scripting; -using Microsoft.Scripting.Generation; namespace IronPython.Runtime { public static partial class Symbols { @@ -96,7 +97,6 @@ internal static string OperatorToReversedSymbol(PythonOperationKind op) { } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal static PythonOperationKind OperatorToReverseOperator(PythonOperationKind op) { switch (op) { @@ -115,6 +115,5 @@ internal static PythonOperationKind OperatorToReverseOperator(PythonOperationKin return op | PythonOperationKind.Reversed; } } - } } diff --git a/src/core/IronPython/Runtime/ThrowingErrorSink.cs b/src/core/IronPython/Runtime/ThrowingErrorSink.cs index a2ea488f0..c2200682b 100644 --- a/src/core/IronPython/Runtime/ThrowingErrorSink.cs +++ b/src/core/IronPython/Runtime/ThrowingErrorSink.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using Microsoft.Scripting; using IronPython.Runtime.Operations; diff --git a/src/core/IronPython/Runtime/Types/CachedNewTypeInfo.cs b/src/core/IronPython/Runtime/Types/CachedNewTypeInfo.cs index b3f1d7337..288ddf33c 100644 --- a/src/core/IronPython/Runtime/Types/CachedNewTypeInfo.cs +++ b/src/core/IronPython/Runtime/Types/CachedNewTypeInfo.cs @@ -2,9 +2,11 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Collections.Generic; -using System.Text; + using Microsoft.Scripting.Utils; namespace IronPython.Runtime.Types { diff --git a/src/core/IronPython/Runtime/Types/ConstructorFunction.cs b/src/core/IronPython/Runtime/Types/ConstructorFunction.cs index 37e936e9a..84b175cac 100644 --- a/src/core/IronPython/Runtime/Types/ConstructorFunction.cs +++ b/src/core/IronPython/Runtime/Types/ConstructorFunction.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System.Collections.Generic; using System.Reflection; -using Microsoft.Scripting.Utils; using System.Text; -using IronPython.Runtime.Operations; -using Microsoft.Scripting; + +using Microsoft.Scripting.Utils; namespace IronPython.Runtime.Types { [PythonType("builtin_function_or_method")] @@ -57,7 +58,5 @@ public override string __doc__ { return sb.ToString(); } } - - } } diff --git a/src/core/IronPython/Runtime/Types/CustomAttributeTracker.cs b/src/core/IronPython/Runtime/Types/CustomAttributeTracker.cs index e211d2514..2ffd2b2d7 100644 --- a/src/core/IronPython/Runtime/Types/CustomAttributeTracker.cs +++ b/src/core/IronPython/Runtime/Types/CustomAttributeTracker.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System.Linq.Expressions; using System; @@ -43,7 +45,7 @@ public override DynamicMetaObject SetValue(OverloadResolverFactory resolverFacto protected override DynamicMetaObject GetBoundValue(OverloadResolverFactory factory, ActionBinder binder, Type instanceType, DynamicMetaObject instance) { return new DynamicMetaObject( Ast.Call( - typeof(PythonOps).GetMethod(nameof(PythonOps.SlotGetValue)), + typeof(PythonOps).GetMethod(nameof(PythonOps.SlotGetValue))!, ((PythonOverloadResolverFactory)factory)._codeContext, AstUtils.Constant(GetSlot(), typeof(PythonTypeSlot)), AstUtils.Convert( @@ -60,11 +62,11 @@ protected override DynamicMetaObject SetBoundValue(OverloadResolverFactory resol return SetBoundValue(resolverFactory, binder, type, value, instance, null); } - protected override DynamicMetaObject SetBoundValue(OverloadResolverFactory factory, ActionBinder binder, Type type, DynamicMetaObject value, DynamicMetaObject instance, DynamicMetaObject errorSuggestion) { + protected override DynamicMetaObject SetBoundValue(OverloadResolverFactory factory, ActionBinder binder, Type type, DynamicMetaObject value, DynamicMetaObject instance, DynamicMetaObject? errorSuggestion) { return new DynamicMetaObject( Expression.Condition( Ast.Call( - typeof(PythonOps).GetMethod(nameof(PythonOps.SlotTrySetValue)), + typeof(PythonOps).GetMethod(nameof(PythonOps.SlotTrySetValue))!, ((PythonOverloadResolverFactory)factory)._codeContext, AstUtils.Constant(GetSlot(), typeof(PythonTypeSlot)), AstUtils.Convert( @@ -79,7 +81,7 @@ protected override DynamicMetaObject SetBoundValue(OverloadResolverFactory facto errorSuggestion.Expression : Expression.Throw( Expression.Call( - typeof(PythonOps).GetMethod(nameof(PythonOps.AttributeErrorForMissingAttribute), new Type[] { typeof(object), typeof(string) }), + typeof(PythonOps).GetMethod(nameof(PythonOps.AttributeErrorForMissingAttribute), new Type[] { typeof(object), typeof(string) })!, instance.Expression, Expression.Constant(Name) ), @@ -101,10 +103,6 @@ internal class CustomAttributeTracker : PythonCustomTracker { private readonly string/*!*/ _name; public CustomAttributeTracker(Type/*!*/ declaringType, string/*!*/ name, PythonTypeSlot/*!*/ slot) { - Debug.Assert(slot != null); - Debug.Assert(declaringType != null); - Debug.Assert(name != null); - _declType = declaringType; _name = name; _slot = slot; @@ -176,9 +174,6 @@ internal class OperatorTracker : PythonCustomTracker { private Type/*!*/ _declType; public OperatorTracker(Type/*!*/ declaringType, string/*!*/ name, bool reversed, params MethodTracker/*!*/[]/*!*/ members) { - Debug.Assert(declaringType != null); - Debug.Assert(members != null); - Debug.Assert(name != null); Debug.Assert(members.Length > 0); _declType = declaringType; diff --git a/src/core/IronPython/Runtime/Types/CustomInstanceDictionaryStorage.cs b/src/core/IronPython/Runtime/Types/CustomInstanceDictionaryStorage.cs index 1048c8d17..5682d9d1e 100644 --- a/src/core/IronPython/Runtime/Types/CustomInstanceDictionaryStorage.cs +++ b/src/core/IronPython/Runtime/Types/CustomInstanceDictionaryStorage.cs @@ -6,10 +6,10 @@ using System; using System.Collections.Generic; -using System.Diagnostics; +using System.Threading; + using Microsoft.Scripting; using Microsoft.Scripting.Runtime; -using System.Threading; namespace IronPython.Runtime.Types { /// diff --git a/src/core/IronPython/Runtime/Types/DynamicBaseTypeAttribute.cs b/src/core/IronPython/Runtime/Types/DynamicBaseTypeAttribute.cs index 07f78895e..be8b6a76a 100644 --- a/src/core/IronPython/Runtime/Types/DynamicBaseTypeAttribute.cs +++ b/src/core/IronPython/Runtime/Types/DynamicBaseTypeAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Runtime.Types { diff --git a/src/core/IronPython/Runtime/Types/FunctionType.cs b/src/core/IronPython/Runtime/Types/FunctionType.cs index fbbf58982..fbd37d3c3 100644 --- a/src/core/IronPython/Runtime/Types/FunctionType.cs +++ b/src/core/IronPython/Runtime/Types/FunctionType.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Runtime.Types { diff --git a/src/core/IronPython/Runtime/Types/IPythonObject.cs b/src/core/IronPython/Runtime/Types/IPythonObject.cs index ddb80f12f..09bd75e1a 100644 --- a/src/core/IronPython/Runtime/Types/IPythonObject.cs +++ b/src/core/IronPython/Runtime/Types/IPythonObject.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System; -using Microsoft.Scripting; +#nullable enable namespace IronPython.Runtime.Types { /// @@ -11,9 +10,7 @@ namespace IronPython.Runtime.Types { /// is not intended for consumption from user programs. /// public interface IPythonObject { - PythonDictionary Dict { - get; - } + PythonDictionary? Dict { get; } /// /// Thread-safe dictionary set. Returns the dictionary set or the previous value if already set or @@ -21,7 +18,7 @@ PythonDictionary Dict { /// /// /// - PythonDictionary SetDict(PythonDictionary dict); + PythonDictionary? SetDict(PythonDictionary dict); /// /// Dictionary replacement. Returns true if replaced, false if the dictionary set isn't supported. /// @@ -29,13 +26,11 @@ PythonDictionary Dict { /// bool ReplaceDict(PythonDictionary dict); - PythonType PythonType { - get; - } + PythonType PythonType { get; } void SetPythonType(PythonType newType); - object[] GetSlots(); + object[]? GetSlots(); object[] GetSlotsCreate(); } } diff --git a/src/core/IronPython/Runtime/Types/InstanceCreator.cs b/src/core/IronPython/Runtime/Types/InstanceCreator.cs index db81d2a18..0db423b9a 100644 --- a/src/core/IronPython/Runtime/Types/InstanceCreator.cs +++ b/src/core/IronPython/Runtime/Types/InstanceCreator.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Runtime.CompilerServices; using System.Threading; @@ -42,11 +44,11 @@ public static InstanceCreator Make(PythonType type) { } internal class UserInstanceCreator : InstanceCreator { - private CallSite> _ctorSite; - private CallSite> _ctorSite0; - private CallSite> _ctorSite1; - private CallSite> _ctorSite2; - private CallSite> _ctorSite3; + private CallSite>? _ctorSite; + private CallSite>? _ctorSite0; + private CallSite>? _ctorSite1; + private CallSite>? _ctorSite2; + private CallSite>? _ctorSite3; public UserInstanceCreator(PythonType/*!*/ type) : base(type) { @@ -134,16 +136,16 @@ internal override object CreateInstance(CodeContext context, params object[] arg } internal override object CreateInstance(CodeContext context, object[] args, string[] names) { - return PythonCalls.CallWithKeywordArgs(context, Type.Ctor, ArrayUtils.Insert(Type, args), names); + return PythonCalls.CallWithKeywordArgs(context, Type.Ctor, ArrayUtils.Insert(Type, args), names)!; } } internal class SystemInstanceCreator : InstanceCreator { - private CallSite> _ctorSite; - private CallSite> _ctorSite0; - private CallSite> _ctorSite1; - private CallSite> _ctorSite2; - private CallSite> _ctorSite3; + private CallSite>? _ctorSite; + private CallSite>? _ctorSite0; + private CallSite>? _ctorSite1; + private CallSite>? _ctorSite2; + private CallSite>? _ctorSite3; public SystemInstanceCreator(PythonType/*!*/ type) : base(type) { @@ -230,7 +232,7 @@ internal override object CreateInstance(CodeContext context, params object[] arg } internal override object CreateInstance(CodeContext context, object[] args, string[] names) { - return PythonCalls.CallWithKeywordArgs(context, Type.Ctor, args, names); + return PythonCalls.CallWithKeywordArgs(context, Type.Ctor, args, names)!; } } } diff --git a/src/core/IronPython/Runtime/Types/OperatorMapping.cs b/src/core/IronPython/Runtime/Types/OperatorMapping.cs index a8448658e..d9aa7c46f 100644 --- a/src/core/IronPython/Runtime/Types/OperatorMapping.cs +++ b/src/core/IronPython/Runtime/Types/OperatorMapping.cs @@ -1,6 +1,12 @@ -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +#nullable enable + +using System; using System.Collections.Generic; -using System.Text; + using IronPython.Runtime.Binding; namespace IronPython.Runtime.Types { @@ -13,7 +19,7 @@ internal class OperatorMapping { private readonly PythonOperationKind _operator; private readonly string _name; - private OperatorMapping(PythonOperationKind op, string name, string altName, Type alternateExpectedType = null) { + private OperatorMapping(PythonOperationKind op, string name, string? altName, Type? alternateExpectedType = null) { _operator = op; _name = name; AlternateName = altName; @@ -23,14 +29,14 @@ private OperatorMapping(PythonOperationKind op, string name, string altName, Typ /// /// Given an operator returns the OperatorMapping associated with the operator or null /// - public static OperatorMapping GetOperatorMapping(PythonOperationKind op) { + public static OperatorMapping? GetOperatorMapping(PythonOperationKind op) { foreach (OperatorMapping info in _infos) { if (info._operator == op) return info; } return null; } - public static OperatorMapping GetOperatorMapping(string name) { + public static OperatorMapping? GetOperatorMapping(string name) { foreach (OperatorMapping info in _infos) { if (info.Name == name || info.AlternateName == name) { return info; @@ -58,14 +64,14 @@ public string Name { /// Gets the secondary method name associated with the method. This method name is /// usually a standard .NET method name with pascal casing (e.g. Add). /// - public string AlternateName { get; } + public string? AlternateName { get; } /// /// Gets the return type that must match for the alternate operator to be valid. /// This is available alternate operators don't have special names and therefore /// could be confused for a normal method which isn't fulfilling the contract. /// - public Type AlternateExpectedType { get; } + public Type? AlternateExpectedType { get; } private static OperatorMapping[] MakeOperatorTable() { List res = new List(); @@ -109,7 +115,7 @@ private static OperatorMapping[] MakeOperatorTable() { res.Add(new OperatorMapping(PythonOperationKind.InPlaceBitwiseAnd, "op_BitwiseAndAssignment", "InPlaceBitwiseAnd")); // &= res.Add(new OperatorMapping(PythonOperationKind.InPlaceBitwiseOr, "op_BitwiseOrAssignment", "InPlaceBitwiseOr")); // |= res.Add(new OperatorMapping(PythonOperationKind.InPlaceTrueDivide, "op_DivisionAssignment", "InPlaceDivide")); // /= - + // these exist just for TypeInfo to map by name res.Add(new OperatorMapping(PythonOperationKind.GetItem, "get_Item", "GetItem")); // not defined res.Add(new OperatorMapping(PythonOperationKind.SetItem, "set_Item", "SetItem")); // not defined diff --git a/src/core/IronPython/Runtime/Types/PythonAssemblyOps.cs b/src/core/IronPython/Runtime/Types/PythonAssemblyOps.cs index c9afd3a8e..a97188371 100644 --- a/src/core/IronPython/Runtime/Types/PythonAssemblyOps.cs +++ b/src/core/IronPython/Runtime/Types/PythonAssemblyOps.cs @@ -2,11 +2,14 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System.Collections.Generic; -using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; + using IronPython.Runtime.Types; + using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Runtime; @@ -40,7 +43,6 @@ public static object GetBoundMember(CodeContext/*!*/ context, Assembly self, str [SpecialName] public static PythonList GetMemberNames(CodeContext/*!*/ context, Assembly self) { - Debug.Assert(self != null); PythonList ret = DynamicHelpers.GetPythonTypeFromType(self.GetType()).GetMemberNames(context); foreach (object o in GetReflectedAssembly(context, self).Keys) { @@ -59,10 +61,9 @@ public static object __repr__(Assembly self) { } private static TopNamespaceTracker GetReflectedAssembly(CodeContext/*!*/ context, Assembly assem) { - Debug.Assert(assem != null); var assemblyMap = GetAssemblyMap(context.LanguageContext as PythonContext); lock (assemblyMap) { - TopNamespaceTracker reflectedAssembly; + TopNamespaceTracker? reflectedAssembly; if (assemblyMap.TryGetValue(assem, out reflectedAssembly)) return reflectedAssembly; @@ -73,5 +74,5 @@ private static TopNamespaceTracker GetReflectedAssembly(CodeContext/*!*/ context return reflectedAssembly; } } - } + } } diff --git a/src/core/IronPython/Runtime/Types/PythonTypeDataSlot.cs b/src/core/IronPython/Runtime/Types/PythonTypeDataSlot.cs index a17d1ee9a..044e84043 100644 --- a/src/core/IronPython/Runtime/Types/PythonTypeDataSlot.cs +++ b/src/core/IronPython/Runtime/Types/PythonTypeDataSlot.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Generic; -using System.Text; +#nullable enable using IronPython.Runtime.Operations; diff --git a/src/core/IronPython/Runtime/Types/PythonTypeTypeSlot.cs b/src/core/IronPython/Runtime/Types/PythonTypeTypeSlot.cs index 3c18fcfbe..6dd358f8b 100644 --- a/src/core/IronPython/Runtime/Types/PythonTypeTypeSlot.cs +++ b/src/core/IronPython/Runtime/Types/PythonTypeTypeSlot.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using IronPython.Runtime.Operations; namespace IronPython.Runtime.Types { @@ -40,7 +42,7 @@ internal override bool TrySetValue(CodeContext context, object instance, PythonT if (!(value is PythonType dt)) throw PythonOps.TypeError("__class__ must be set to a class, not '{0}' object", PythonOps.GetPythonTypeName(value)); - if(dt.UnderlyingSystemType != DynamicHelpers.GetPythonType(instance).UnderlyingSystemType) + if (dt.UnderlyingSystemType != DynamicHelpers.GetPythonType(instance).UnderlyingSystemType) throw PythonOps.TypeErrorForIncompatibleObjectLayout("__class__ assignment", DynamicHelpers.GetPythonType(instance), dt.UnderlyingSystemType); sdo.SetPythonType(dt); diff --git a/src/core/IronPython/Runtime/Types/ResolvedMember.cs b/src/core/IronPython/Runtime/Types/ResolvedMember.cs index 159baf3c3..62dfaa6ee 100644 --- a/src/core/IronPython/Runtime/Types/ResolvedMember.cs +++ b/src/core/IronPython/Runtime/Types/ResolvedMember.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Diagnostics; +#nullable enable using Microsoft.Scripting.Actions; @@ -16,9 +16,6 @@ internal class ResolvedMember { public static readonly ResolvedMember[]/*!*/ Empty = System.Array.Empty(); public ResolvedMember(string/*!*/ name, MemberGroup/*!*/ member) { - Debug.Assert(name != null); - Debug.Assert(member != null); - Name = name; Member = member; } diff --git a/src/core/IronPython/Runtime/Types/SlotFieldAttribute.cs b/src/core/IronPython/Runtime/Types/SlotFieldAttribute.cs index ee6bb3783..6477a5bd6 100644 --- a/src/core/IronPython/Runtime/Types/SlotFieldAttribute.cs +++ b/src/core/IronPython/Runtime/Types/SlotFieldAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Runtime.Types { diff --git a/src/core/IronPython/Runtime/Types/TypeCache.Generated.cs b/src/core/IronPython/Runtime/Types/TypeCache.Generated.cs index a1c36d561..8de6b9ba0 100644 --- a/src/core/IronPython/Runtime/Types/TypeCache.Generated.cs +++ b/src/core/IronPython/Runtime/Types/TypeCache.Generated.cs @@ -2,14 +2,15 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System; +#nullable enable -using Microsoft.Scripting.Runtime; +using System; +using System.Numerics; using IronPython.Modules; using IronPython.Runtime.Exceptions; -using System.Numerics; +using Microsoft.Scripting.Runtime; namespace IronPython.Runtime.Types { public static class TypeCache { @@ -18,33 +19,33 @@ public static class TypeCache { // *** BEGIN GENERATED CODE *** // generated by function: gen_typecache_storage from: generate_typecache.py - private static PythonType array; - private static PythonType builtinfunction; - private static PythonType pythondictionary; - private static PythonType frozensetcollection; - private static PythonType pythonfunction; - private static PythonType builtin; - private static PythonType obj; - private static PythonType setcollection; - private static PythonType pythontype; - private static PythonType str; - private static PythonType bytes; - private static PythonType bytearray; - private static PythonType pythontuple; - private static PythonType weakreference; - private static PythonType pythonlist; - private static PythonType pythonmodule; - private static PythonType method; - private static PythonType enumerate; - private static PythonType intType; - private static PythonType singleType; - private static PythonType doubleType; - private static PythonType biginteger; - private static PythonType complex; - private static PythonType super; - private static PythonType nullType; - private static PythonType boolType; - private static PythonType baseException; + private static PythonType? array; + private static PythonType? builtinfunction; + private static PythonType? pythondictionary; + private static PythonType? frozensetcollection; + private static PythonType? pythonfunction; + private static PythonType? builtin; + private static PythonType? obj; + private static PythonType? setcollection; + private static PythonType? pythontype; + private static PythonType? str; + private static PythonType? bytes; + private static PythonType? bytearray; + private static PythonType? pythontuple; + private static PythonType? weakreference; + private static PythonType? pythonlist; + private static PythonType? pythonmodule; + private static PythonType? method; + private static PythonType? enumerate; + private static PythonType? intType; + private static PythonType? singleType; + private static PythonType? doubleType; + private static PythonType? biginteger; + private static PythonType? complex; + private static PythonType? super; + private static PythonType? nullType; + private static PythonType? boolType; + private static PythonType? baseException; // *** END GENERATED CODE *** @@ -55,195 +56,86 @@ public static class TypeCache { // *** BEGIN GENERATED CODE *** // generated by function: gen_typecache from: generate_typecache.py - public static PythonType Array { - get { - if (array == null) array = DynamicHelpers.GetPythonTypeFromType(typeof(Array)); - return array; - } - } - - public static PythonType BuiltinFunction { - get { - if (builtinfunction == null) builtinfunction = DynamicHelpers.GetPythonTypeFromType(typeof(BuiltinFunction)); - return builtinfunction; - } - } - - public static PythonType Dict { - get { - if (pythondictionary == null) pythondictionary = DynamicHelpers.GetPythonTypeFromType(typeof(PythonDictionary)); - return pythondictionary; - } - } - - public static PythonType FrozenSet { - get { - if (frozensetcollection == null) frozensetcollection = DynamicHelpers.GetPythonTypeFromType(typeof(FrozenSetCollection)); - return frozensetcollection; - } - } - - public static PythonType Function { - get { - if (pythonfunction == null) pythonfunction = DynamicHelpers.GetPythonTypeFromType(typeof(PythonFunction)); - return pythonfunction; - } - } - - public static PythonType Builtin { - get { - if (builtin == null) builtin = DynamicHelpers.GetPythonTypeFromType(typeof(Builtin)); - return builtin; - } - } - - public static PythonType Object { - get { - if (obj == null) obj = DynamicHelpers.GetPythonTypeFromType(typeof(Object)); - return obj; - } - } - - public static PythonType Set { - get { - if (setcollection == null) setcollection = DynamicHelpers.GetPythonTypeFromType(typeof(SetCollection)); - return setcollection; - } - } - - public static PythonType PythonType { - get { - if (pythontype == null) pythontype = DynamicHelpers.GetPythonTypeFromType(typeof(PythonType)); - return pythontype; - } - } - - public static PythonType String { - get { - if (str == null) str = DynamicHelpers.GetPythonTypeFromType(typeof(String)); - return str; - } - } - - public static PythonType Bytes { - get { - if (bytes == null) bytes = DynamicHelpers.GetPythonTypeFromType(typeof(Bytes)); - return bytes; - } - } - - public static PythonType ByteArray { - get { - if (bytearray == null) bytearray = DynamicHelpers.GetPythonTypeFromType(typeof(ByteArray)); - return bytearray; - } - } - - public static PythonType PythonTuple { - get { - if (pythontuple == null) pythontuple = DynamicHelpers.GetPythonTypeFromType(typeof(PythonTuple)); - return pythontuple; - } - } - - public static PythonType WeakReference { - get { - if (weakreference == null) weakreference = DynamicHelpers.GetPythonTypeFromType(typeof(WeakReference)); - return weakreference; - } - } - - public static PythonType PythonList { - get { - if (pythonlist == null) pythonlist = DynamicHelpers.GetPythonTypeFromType(typeof(PythonList)); - return pythonlist; - } - } - - public static PythonType Module { - get { - if (pythonmodule == null) pythonmodule = DynamicHelpers.GetPythonTypeFromType(typeof(PythonModule)); - return pythonmodule; - } - } - - public static PythonType Method { - get { - if (method == null) method = DynamicHelpers.GetPythonTypeFromType(typeof(Method)); - return method; - } - } - - public static PythonType Enumerate { - get { - if (enumerate == null) enumerate = DynamicHelpers.GetPythonTypeFromType(typeof(Enumerate)); - return enumerate; - } - } - - public static PythonType Int32 { - get { - if (intType == null) intType = DynamicHelpers.GetPythonTypeFromType(typeof(Int32)); - return intType; - } - } - - public static PythonType Single { - get { - if (singleType == null) singleType = DynamicHelpers.GetPythonTypeFromType(typeof(Single)); - return singleType; - } - } - - public static PythonType Double { - get { - if (doubleType == null) doubleType = DynamicHelpers.GetPythonTypeFromType(typeof(Double)); - return doubleType; - } - } - - public static PythonType BigInteger { - get { - if (biginteger == null) biginteger = DynamicHelpers.GetPythonTypeFromType(typeof(BigInteger)); - return biginteger; - } - } - - public static PythonType Complex { - get { - if (complex == null) complex = DynamicHelpers.GetPythonTypeFromType(typeof(Complex)); - return complex; - } - } - - public static PythonType Super { - get { - if (super == null) super = DynamicHelpers.GetPythonTypeFromType(typeof(Super)); - return super; - } - } - - public static PythonType Null { - get { - if (nullType == null) nullType = DynamicHelpers.GetPythonTypeFromType(typeof(DynamicNull)); - return nullType; - } - } - - public static PythonType Boolean { - get { - if (boolType == null) boolType = DynamicHelpers.GetPythonTypeFromType(typeof(Boolean)); - return boolType; - } - } - - public static PythonType BaseException { - get { - if (baseException == null) baseException = DynamicHelpers.GetPythonTypeFromType(typeof(PythonExceptions.BaseException)); - return baseException; - } - } + public static PythonType Array + => array ??= DynamicHelpers.GetPythonTypeFromType(typeof(Array)); + + public static PythonType BuiltinFunction + => builtinfunction ??= DynamicHelpers.GetPythonTypeFromType(typeof(BuiltinFunction)); + + public static PythonType Dict + => pythondictionary ??= DynamicHelpers.GetPythonTypeFromType(typeof(PythonDictionary)); + + public static PythonType FrozenSet + => frozensetcollection ??= DynamicHelpers.GetPythonTypeFromType(typeof(FrozenSetCollection)); + + public static PythonType Function + => pythonfunction ??= DynamicHelpers.GetPythonTypeFromType(typeof(PythonFunction)); + + public static PythonType Builtin + => builtin ??= DynamicHelpers.GetPythonTypeFromType(typeof(Builtin)); + + public static PythonType Object + => obj ??= DynamicHelpers.GetPythonTypeFromType(typeof(Object)); + + public static PythonType Set + => setcollection ??= DynamicHelpers.GetPythonTypeFromType(typeof(SetCollection)); + + public static PythonType PythonType + => pythontype ??= DynamicHelpers.GetPythonTypeFromType(typeof(PythonType)); + + public static PythonType String + => str ??= DynamicHelpers.GetPythonTypeFromType(typeof(String)); + + public static PythonType Bytes + => bytes ??= DynamicHelpers.GetPythonTypeFromType(typeof(Bytes)); + + public static PythonType ByteArray + => bytearray ??= DynamicHelpers.GetPythonTypeFromType(typeof(ByteArray)); + + public static PythonType PythonTuple + => pythontuple ??= DynamicHelpers.GetPythonTypeFromType(typeof(PythonTuple)); + + public static PythonType WeakReference + => weakreference ??= DynamicHelpers.GetPythonTypeFromType(typeof(WeakReference)); + + public static PythonType PythonList + => pythonlist ??= DynamicHelpers.GetPythonTypeFromType(typeof(PythonList)); + + public static PythonType Module + => pythonmodule ??= DynamicHelpers.GetPythonTypeFromType(typeof(PythonModule)); + + public static PythonType Method + => method ??= DynamicHelpers.GetPythonTypeFromType(typeof(Method)); + + public static PythonType Enumerate + => enumerate ??= DynamicHelpers.GetPythonTypeFromType(typeof(Enumerate)); + + public static PythonType Int32 + => intType ??= DynamicHelpers.GetPythonTypeFromType(typeof(Int32)); + + public static PythonType Single + => singleType ??= DynamicHelpers.GetPythonTypeFromType(typeof(Single)); + + public static PythonType Double + => doubleType ??= DynamicHelpers.GetPythonTypeFromType(typeof(Double)); + + public static PythonType BigInteger + => biginteger ??= DynamicHelpers.GetPythonTypeFromType(typeof(BigInteger)); + + public static PythonType Complex + => complex ??= DynamicHelpers.GetPythonTypeFromType(typeof(Complex)); + + public static PythonType Super + => super ??= DynamicHelpers.GetPythonTypeFromType(typeof(Super)); + + public static PythonType Null + => nullType ??= DynamicHelpers.GetPythonTypeFromType(typeof(DynamicNull)); + + public static PythonType Boolean + => boolType ??= DynamicHelpers.GetPythonTypeFromType(typeof(Boolean)); + public static PythonType BaseException + => baseException ??= DynamicHelpers.GetPythonTypeFromType(typeof(PythonExceptions.BaseException)); // *** END GENERATED CODE *** diff --git a/src/core/IronPython/Runtime/UnboundNameException.cs b/src/core/IronPython/Runtime/UnboundNameException.cs index a7cb6590f..a4e8162f5 100644 --- a/src/core/IronPython/Runtime/UnboundNameException.cs +++ b/src/core/IronPython/Runtime/UnboundNameException.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Runtime.Serialization; diff --git a/src/core/IronPython/Runtime/WrapperDescriptorAttribute.cs b/src/core/IronPython/Runtime/WrapperDescriptorAttribute.cs index abc422cb6..2a32e92f7 100644 --- a/src/core/IronPython/Runtime/WrapperDescriptorAttribute.cs +++ b/src/core/IronPython/Runtime/WrapperDescriptorAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Runtime {