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** | [](https://dotnet.visualstudio.com/IronLanguages/_build/latest?definitionId=43) [](https://github.com/IronLanguages/ironpython3/actions?workflow=CI) |
-| **Downloads** | [](https://www.nuget.org/packages/IronPython/3.4.0) [](https://github.com/IronLanguages/ironpython3/releases/latest)|
+| **Downloads** | [](https://www.nuget.org/packages/IronPython/latest) [](https://github.com/IronLanguages/ironpython3/releases/latest)|
| **Help** | [](https://gitter.im/IronLanguages/ironpython) [](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